且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算两个经纬度点之间的距离?(Haversine 公式)

更新时间:2022-12-09 07:46:54

我需要为我的项目计算很多点之间的距离,所以我继续尝试优化代码,我在这里找到了.平均而言,在不同浏览器中,我的新实现运行速度比最受好评的答案快 2 倍.

I needed to calculate a lot of distances between the points for my project, so I went ahead and tried to optimize the code, I have found here. On average in different browsers my new implementation runs 2 times faster than the most upvoted answer.

function distance(lat1, lon1, lat2, lon2) {
  var p = 0.017453292519943295;    // Math.PI / 180
  var c = Math.cos;
  var a = 0.5 - c((lat2 - lat1) * p)/2 + 
          c(lat1 * p) * c(lat2 * p) * 
          (1 - c((lon2 - lon1) * p))/2;

  return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
}

您可以使用我的 jsPerf 并查看结果.

You can play with my jsPerf and see the results here.

最近我需要在 python 中做同样的事情,所以这里是一个 python 实现:

Recently I needed to do the same in python, so here is a python implementation:

from math import cos, asin, sqrt, pi

def distance(lat1, lon1, lat2, lon2):
    p = pi/180
    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2
    return 12742 * asin(sqrt(a)) #2*R*asin...

为了完整起见:***上的Haversine.

And for the sake of completeness: Haversine on Wikipedia.