我对Google地图很新,我想计算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;
}
以上代码无法给出两个地方之间的准确距离。找到距离的另一种方法是什么,请给我任何建议。
答案 0 :(得分:16)
@Chirag Patel
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
答案 1 :(得分: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);
答案 2 :(得分:0)
只需使用Location.distanceTo(位置),它就会为您提供两个不同位置之间的真正距离。
答案 3 :(得分: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
答案 4 :(得分:-1)
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);