7

我对谷歌地图很陌生,我想计算android中两个地方之间的距离。

为此,我得到了两个位置 lat 和 lag 位置,为此我编写了以下代码:

private double getDistance(double lat1, double lat2, double lon1, double lon2) {
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = Math.toRadians(lon2 - lon1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double temp = 6371 * c;
    temp=temp*0.621;
    return temp;
}

上面的代码不能给出两地之间的准确距离。找到距离的另一种方法是什么,请给我任何建议。

4

5 回答 5

19

@奇拉格帕特尔

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);   // in meters
distance = locationA.distanceTo(locationB)/1000;   // in km
于 2012-11-03T14:35:46.443 回答
5

使用以下代码,您可以找到距离,但您想以公里为单位进行转换。

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);
于 2012-11-03T11:03:02.680 回答
0

只需使用 Location.distanceTo(Location) 它将为您提供两个不同位置之间的真正距离。

于 2014-07-11T10:09:17.213 回答
0

使用代码查找距离米到公里和公里到英里

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);   // in meters
distance = locationA.distanceTo(locationB)/1000;   // in km
distance = locationA.distanceTo(locationB)/1609.344;   // in miles
于 2018-08-14T11:36:22.617 回答
0
            Location locationA = new Location("Point A");
            locationA.setLatitude(fromLatitude);
            locationA.setLongitude(fromLongitude);


            Location locationB = new Location("point B");
            locationB.setLatitude(toLatitude);
            locationB.setLongitude(toLongitude);


            distance = locationA.distanceTo(locationB);
于 2019-02-18T07:13:37.313 回答