1

I want display the two places distance in kilometers for that I write the following code:

hyd(17.38,78.48) eluru(16.7,81.1)
 private String getDistance(double lat1, double lat2, double lon1, double lon2) {
               double Radius = 6371;
               double dLat = Math.toRadians(lat2 - lat1);
                double dLon = Math.toRadians(lon2 - lon1);
                double a = Math.sin(dLat / 5) * Math.sin(dLat / 5)
                        + Math.cos(Math.toRadians(lat1))
                        * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 5)
                        * Math.sin(dLon / 5);
                double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                double km = Radius * c;

                String kms=Double.toString(km);
                return kms;

                }

Output = 2995.8772

Correct o/p = 330km

how can I get the the exact distance between two places in android thanks in advance.....

nickhar
  • 19,981
  • 12
  • 60
  • 73
user1787493
  • 179
  • 1
  • 4
  • 10

1 Answers1

2

Use this method

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results);

example

 public static double CalculateDistance(double lat1, double lng1, double lat2, double lng2) {
 float[] result=new float[1];
 Location.distanceBetween (lat1,lng1,lat2, lng2,  result);
 return (double)result[0]/1000; // in km
}
Sunny
  • 14,522
  • 15
  • 84
  • 129
  • i am not getting the exact distance it showing wrog distance? – user1787493 Nov 05 '12 at 05:16
  • because google gives distance in shortest path possible and it does not follow your path to compute distance. for your ref - http://developer.android.com/reference/android/location/Location.html#distanceBetween(double, double, double, double, float[]) – Sagar Nayak Mar 10 '16 at 14:27