计算android中两个经纬度点之间的距离
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22577075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating the distance between two latitude and longitude points in android
提问by Devrath
How can i find the distance between two
latitude
& longitude
points
我怎样才能找到two
latitude
&longitude
点之间的距离
For one of the latitude & longitude points i have it in database & another one i want to use current position of the mobile
对于我在数据库中的纬度和经度点之一,另一个我想使用移动设备的当前位置
Which one should i need to use them among below::
我应该在以下哪一个中使用它们:
- android location provider
- Google API
- Mathematical Calculation
- 安卓位置提供者
- 谷歌API
- 数学计算
note:: Any demo code sample will be useful
注意:: 任何演示代码示例都会有用
回答by David
You can use the built in algorithm:
您可以使用内置算法:
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) ;
update: (I don't have any error with this)
更新:(我对此没有任何错误)
LatLng latLngA = new LatLng(12.3456789,98.7654321);
LatLng latLngB = new LatLng(98.7654321,12.3456789);
Location locationA = new Location("point A");
locationA.setLatitude(latLngA.latitude);
locationA.setLongitude(latLngA.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(latLngB.latitude);
locationB.setLongitude(latLngB.longitude);
double distance = locationA.distanceTo(locationB);
回答by Emilio
You can use the Haversine algorithm. Another user has already coded a solution for this:
您可以使用Haversine 算法。另一个用户已经为此编写了一个解决方案:
public double CalculationByDistance(double initialLat, double initialLong,
double finalLat, double finalLong){
int R = 6371; // km
double dLat = toRadians(finalLat-initialLat);
double dLon = toRadians(finalLong-initialLong);
lat1 = toRadians(lat1);
lat2 = toRadians(lat2);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
public double toRadians(deg) {
return deg * (Math.PI/180)
}