Reputation: 701
I have latitude and longitude of two places. Can i calculate the distance between them in android?
Upvotes: 0
Views: 1084
Reputation: 38727
This API is what you want:
(NB: It's static... no Location object instances are required)
Upvotes: 3
Reputation: 15008
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
Upvotes: 4
Reputation: 12668
Use search:
How can i calculate the distance between two gps points in Java?
Upvotes: 3