0

I have latitude and longitude of two places. Can i calculate the distance between them in android?

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
mohammedsuhail
  • 701
  • 2
  • 11
  • 23
  • 1
    possible duplicate of [How can i calculate the distance between two gps points in Java?](http://stackoverflow.com/questions/3715521/how-can-i-calculate-the-distance-between-two-gps-points-in-java) – gbjbaanb Oct 18 '10 at 12:16

3 Answers3

4

What you're looking for is the haversine formula which gives the distance between two points on a sphere using their latitudes and longitudes.

Haversine Formula:

R = earth's radius (mean radius = 6371km)
Δlat = lat2 − lat1
Δlong = long2 − long1
a = sin²(Δlat/2) + cos(lat1)*cos(lat2)*sin²(Δlong/2)
c = 2*atan2(√a, √(1−a))
d = R*c

In JavaScript:

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad(); 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

http://www.movable-type.co.uk/scripts/latlong.html

Tyler Treat
  • 14,640
  • 15
  • 80
  • 115
3

Use search:

How can i calculate the distance between two gps points in Java?

Community
  • 1
  • 1
Select0r
  • 12,234
  • 11
  • 45
  • 68
3

This API is what you want:

http://developer.android.com/reference/android/location/Location.html#distanceBetween(double,%20double,%20double,%20double,%20float[])

(NB: It's static... no Location object instances are required)

Reuben Scratton
  • 38,595
  • 9
  • 77
  • 86