Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between 2 places on Android Map

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?

like image 456
User Avatar asked Dec 05 '25 07:12

User


1 Answers

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).

like image 162
Mattias Isegran Bergander Avatar answered Dec 07 '25 19:12

Mattias Isegran Bergander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!