计算两个经纬度点之间的距离?(Haversine 公式) [英] Calculate distance between two latitude-longitude points? (Haversine formula)

查看:63
本文介绍了计算两个经纬度点之间的距离?(Haversine 公式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算经纬度指定的两点之间的距离?

How do I calculate the distance between two points specified by latitude and longitude?

为了澄清起见,我想要以公里为单位的距离;这些点使用 WGS84 系统,我想了解可用方法的相对准确度.

For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.

推荐答案

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

这篇关于计算两个经纬度点之间的距离?(Haversine 公式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆