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

Find closest city to given longitude/latitude

本文关键字:纬度 最近 城市 经度 查找      更新时间:2023-09-26

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

有什么想法可以使用javascript来做到这一点吗?

thx。rttmax

从这个网站,你可以使用Haversine公式:

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

可以用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;

然后对所有使用循环的城市都这样做,并找到最小的。