distance between two locations is not right?

2019-07-23 03:11发布

i get two locations using this :

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

then i compute the distance between them , but the distance is not true

public static float calculateDistance(double e, double f, double g, double h)
{
    float dLat = (float) Math.toRadians(g - e);
    float dLon = (float) Math.toRadians(h - f);
    float a =
            (float) (Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(e))
                    * Math.cos(Math.toRadians(g)) * Math.sin(dLon / 2) * Math.sin(dLon / 2));
    float c = (float) (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
    float d = 6371 * c;
    return d;
}

(32.2163799,35.0420986) (31.9210915,35.2037014)

the result 36.193707 km but the actual is more than that , approximately 85 km

2条回答
戒情不戒烟
2楼-- · 2019-07-23 03:42

You can use standart function for this:

Location location1 = new Location("<provider name");
location1.setLatitude(lat1);
location1.setLongitude(lng1);

Location location2 = new Location("<provider name");
location2.setLatitude(lat2);
location2.setLongitude(lng2);

float distance = location1.distanceTo(location2);

More info:http://developer.android.com/reference/android/location/Location.html#distanceTo%28android.location.Location%29

Or distance between function: http://developer.android.com/reference/android/location/Location.html#distanceBetween%28double,%20double,%20double,%20double,%20float[]%29

查看更多
Summer. ? 凉城
3楼-- · 2019-07-23 03:47

Use static method distanceBetween() to get distance in meters

float[] results = new float[3];
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
float distanceInMeters = results[0]


Note that the results array packs together several values relating to the distance between the two points:

  - results[0] -  distance in meters
  - results[1] -  initial bearing angle of the shortest path between them
  - results[2] -  final bearing angle of the shortest path between them
查看更多
登录 后发表回答