0

I'm fetching the user's best current position using this snippet:

    LocationManager ltrLocationer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    Location locLocation = ltrLocationer.getLastKnownLocation(ltrLocationer.getBestProvider(criteria, true));

I have a two Double objects containing a latitude and a longitude respectively. I'd like to check the distance in metres between the current coordinates and the the aforementioned value. How can I do this?

This sounded like a pretty simple thing to accomplish but I haven't been able to find an example illustrating this. Thanks.

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382

3 Answers3

2

The Location object has a distance method. Use that, it does the math for you. If you have your coordinates as douboles, use the static function Location.distanceBetween

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
1

take a look here :GPS Coordinates to Meters Also here is a wikipedia article about the equation used to do the calculations: Haversine formula

Mr.Me
  • 9,192
  • 5
  • 39
  • 51
0

Check this method, this will give you the distance in a straight line.

public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
        * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;

return dist;
}

If you want a road distance this operation is a little bit more difficult and will involve a call to Google Direction API services.

Emil Adz
  • 40,709
  • 36
  • 140
  • 187