给定两点经纬度坐标计算距离

最近在作一个实时的运筹优化项目,须要针对给定的两点经纬度,计算其距离。python

这里我参考了维基百科的Haversine formula公式:git

{\displaystyle {\begin{aligned}d&=2r\arcsin \left({\sqrt {\operatorname {hav} (\varphi _{2}-\varphi _{1})+\cos(\varphi _{1})\cos(\varphi _{2})\operatorname {hav} (\lambda _{2}-\lambda _{1})}}\right)\\&=2r\arcsin \left({\sqrt {\sin ^{2}\left({\frac {\varphi _{2}-\varphi _{1}}{2}}\right)+\cos(\varphi _{1})\cos(\varphi _{2})\sin ^{2}\left({\frac {\lambda _{2}-\lambda _{1}}{2}}\right)}}\right)\end{aligned}}}

其中:github

  • φ1, φ2: latitude of point 1 and latitude of point 2,
  • λ1, λ2: longitude of point 1 and longitude of point 2.

所以这里我根据以上公式,写出了python的计算距离模块以下:优化

from math import *

def get_distance(origin, destination):
    # 根据经纬度计算两个点距离
    lon1 = radians(float(destination[0]))
    lon2 = radians(float(origin[0]))
    lat1 = radians(float(destination[1]))
    lat2 = radians(float(origin[1]))
    dlon = lon1 - lon2
    dlat = lat1 - lat2
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    dist = 2 * asin(sqrt(a))*6371*1000
    return dist

另外,我还把不少工做中用到的基本模块传到了github:https://github.com/kunkun1230/Basic-founctionscode

欢迎交流star!orm