I need to calculate distance between current location and the destination. I have the latitude and longitude of current and destination locations. I found the below code from SO and internet while searching. But the calculation give 1366 km while the google maps gives 1675 km between 2 locations. Can someone help how can I calculate accurate distance. The destinations are world wide including my current city locations.
//Distance in Kilometers
fun distanceInKms ( lat1: Double, long1: Double, lat2: Double, long2: Double) : Double
{
val degToRad= Math.PI / 180.0;
val phi1 = lat1 * degToRad;
val phi2 = lat2 * degToRad;
val lam1 = long1 * degToRad;
val lam2 = long2 * degToRad;
return 6371.01 * Math.acos( Math.sin(phi1) * Math.sin(phi2) + Math.cos(phi1) * Math.cos(phi2) * Math.cos(lam2 - lam1) );
}
Can someone help me out with this please?
Use the android.location.Location class, available since API level 1 in Android. It has a static distanceBetween method doing it all for you.
See: http://developer.android.com/reference/android/location/Location.html
float[] results = new float[1];
android.location.Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
//distance in meters now in results[0]
Divide by 1000 to get it in kilometers (km).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With