Android – How to Find Distance Between Two Geopoints

androidgeolocation

double distance;  

Location locationA = new Location("point A");  

locationA.setLatitude(latA);  
locationA.setLongitude(lngA);  

Location locationB = new Location("point B");  

locationB.setLatitude(latB);  
LocationB.setLongitude(lngB);  

distance = locationA.distanceTo(locationB);  

the above code is not working and i am getting 0.0 Km as distance?
Also in the constructor of the location class, what does the string provider mean.
In the above code i am using PointA and PointB as the providers.

why is the above code not working?

thank you in advance.

LOGCAT
05-09 17:48:56.144: INFO/current loc(1573): lat 0.0 lng 0.0
05-09 17:48:56.155: INFO/checklocation loc(1573): lat 54.4288665 lng 10.169366

Best Answer

Just a quick snippet since I didn't see a complete and simple solution with GeoPoints above:

public float getDistanceInMiles(GeoPoint p1, GeoPoint p2) {
    double lat1 = ((double)p1.getLatitudeE6()) / 1e6;
    double lng1 = ((double)p1.getLongitudeE6()) / 1e6;
    double lat2 = ((double)p2.getLatitudeE6()) / 1e6;
    double lng2 = ((double)p2.getLongitudeE6()) / 1e6;
    float [] dist = new float[1];
    Location.distanceBetween(lat1, lng1, lat2, lng2, dist);
    return dist[0] * 0.000621371192f;
}

If you want meters, just return dist[0] directly.