找到给定经纬度最近的城市

4

我有一组包含10个城市的经纬度信息,想要找出其中距离给定经纬度最近的城市。

有没有什么使用JavaScript实现的思路呢?

谢谢。rttmax


我不知道从哪里开始... - rttmax
1个回答

4

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

a = sin²(Δφ/2) + cos1).cos2).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;

然后使用循环为所有城市执行此操作,并找到最小值。

1
非常感谢!我需要添加:Number.prototype.toRad = function () { return this * Math.PI / 180; },就像这里提到的一样:http://stackoverflow.com/questions/6889922/how-to-deal-with-brng-torad-is-not-a-function - rttmax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接