我有一个数据库,里面有一个纬度和经度列表
-DeviceName
-Latitude
-Longitude
考虑到我当前设备的纬度和经度,我想获得数据库列表中距离/接近X公里的所有设备。
如何计算我所在位置与其他位置的接近度?
我想你想看看这个令人惊叹的演示。它会告诉你如何使用haversine公式来计算地球表面的距离,包括曲率,以及如何避免数据库查询中的一些常见错误等。
如果你想要原始代码,这应该会对你有所帮助:
private static Double rad2deg(Double rad) {
return (rad / Math.PI * 180.0);
}
private static Double deg2rad(Double deg) {
return (deg * Math.PI / 180.0);
}
private const Double kEarthRadiusKms = 6376.5;
private static Double CalculateDistance(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
double theta = longitude1 - longitude2;
double dist = Math.Sin(deg2rad(latitude1)) * Math.Sin(deg2rad(latitude2)) + Math.Cos(deg2rad(latitude1)) * Math.Cos(deg2rad(latitude2)) * Math.Cos(deg2rad(theta));
dist = Math.Acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
return (dist);
}