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.

Tags:

Android