How to calculate distance between two locations using their longitude and latitude value
There is an android.location.Location.distanceBetween()
method which does this quite well.
Android Developer Docs: Location
Here getting distance in miles (mi)
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
Try this code.
startPoint.distanceTo(endPoint) function returns the distance between those places in meters.
Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);
Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);
double distance=startPoint.distanceTo(endPoint);
here "distance" is our required result in Meters. I hope it will work for android.
in build.gradle:
compile 'com.google.maps.android:android-maps-utils:0.4'
and then:
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
return SphericalUtil.computeDistanceBetween(point1, point2);
}
If you have two Location Objects Location loc1
and Location loc2
you do
float distance = loc1.distanceTo(loc2);
If you have longitude and latitude values you use the static distanceBetween()
function
float[] results = new float[1];
Location.distanceBetween(startLatitude, startLongitude,
endLatitude, endLongitude, results);
float distance = results[0];