distance between two locations is not right?

橙三吉。 提交于 2019-12-13 01:26:28

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/24714204/distance-between-two-locations-is-not-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!