我有一组包含10个城市的经纬度信息,想要找出其中距离给定经纬度最近的城市。
有没有什么使用JavaScript实现的思路呢?
谢谢。rttmax
我有一组包含10个城市的经纬度信息,想要找出其中距离给定经纬度最近的城市。
有没有什么使用JavaScript实现的思路呢?
谢谢。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;
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