Calculate distance in meters when you know longitude and latitude in java [duplicate]
Solution 1:
Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Solution 2:
You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.
Implementation goes like this:
import org.gavaghan.geodesy.*;
...
GeodeticCalculator geoCalc = new GeodeticCalculator();
Ellipsoid reference = Ellipsoid.WGS84;
GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A
GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B
double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B
The resulting distance is in meters.
Solution 3:
In C++ it is done like this:
#define LOCAL_PI 3.1415926535897932385
double ToRadians(double degrees)
{
double radians = degrees * LOCAL_PI / 180;
return radians;
}
double DirectDistance(double lat1, double lng1, double lat2, double lng2)
{
double earthRadius = 3958.75;
double dLat = ToRadians(lat2-lat1);
double dLng = ToRadians(lng2-lng1);
double a = sin(dLat/2) * sin(dLat/2) +
cos(ToRadians(lat1)) * cos(ToRadians(lat2)) *
sin(dLng/2) * sin(dLng/2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double dist = earthRadius * c;
double meterConversion = 1609.00;
return dist * meterConversion;
}