查找距离给定经度/纬度的最近城市

时间:2021-05-15 16:02:12

I have a set of 10 citys and want to find out which one is the closest to a given longitude/latitude.

我有一组10个城市,想要找出哪一个最接近给定的经度/纬度。

Any ideas how to do that using javascript?

任何想法如何使用javascript做到这一点?

thx. rttmax

谢谢。 rttmax

1 个解决方案

#1


4  

From this site, you can use the Haversine formula:

在此站点中,您可以使用Haversine公式:

a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
c = 2.atan2(√a, √(1−a))
d = R.c

Which can be implemented in Javascript:

哪个可以在Javascript中实现:

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

Then just do that for all of the cities using a loop and find the smallest.

然后只需使用循环为所有城市做到这一点并找到最小的城市。

#1


4  

From this site, you can use the Haversine formula:

在此站点中,您可以使用Haversine公式:

a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
c = 2.atan2(√a, √(1−a))
d = R.c

Which can be implemented in Javascript:

哪个可以在Javascript中实现:

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

Then just do that for all of the cities using a loop and find the smallest.

然后只需使用循环为所有城市做到这一点并找到最小的城市。