Haversine公式

 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 }

 

这段代码可以计算地球上两个位置之间的距离。

posted @ 2012-08-30 11:05  小猩猩君  阅读(6463)  评论(0编辑  收藏  举报