1 Number.prototype.toRadians =
function() {
2 return this * Math.PI / 180
;
3 }
4
5 function distance(latitude1, longitude1, latitude2, longitude2) {
6 //R是地球的半径,以KM为单位
7 var R = 6371
;
8
9 var deltaLatitude = (latitude2 -
latitude1).toRadians();
10 var deltaLongitude = (longitude2 -
longitude1).toRadians();
11 latitude1 = latitude1.toRadians(), latitude2 =
latitude2.toRadians();
12
13 var a = Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(deltaLongitude / 2) * Math.sin(deltaLongitude / 2
);
14 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 -
a));
15 var d = R *
c;
16 return d;
17 }
这段代码可以计算地球上两个位置之间的距离。
转载于:https://www.cnblogs.com/qzsonline/archive/2012/08/30/2663306.html
相关资源:haversine-rest-api:此Api比较“ Haversine”公式和MongoDB地理空间索引返回的结果-源码