Haversine公式
半正矢公式(haversine equation)用于计算两经纬度点的距离,公式为:
d
=
2
r
argsin
(
sin
2
(
l
a
t
2
−
l
a
t
1
2
)
+
cos
(
l
a
t
2
)
cos
(
l
a
t
1
)
sin
2
(
l
o
n
2
−
l
o
n
1
2
)
)
d=2r\operatorname{argsin}(\sqrt{\sin^2(\frac{lat2-lat1}{2})+\cos(lat2)\cos(lat1)\sin^2(\frac{lon2-lon1}{2})})
d=2rargsin(sin2(2lat2−lat1)+cos(lat2)cos(lat1)sin2(2lon2−lon1)
)
式子中R为半径。
python代码实现
地球半径为6378km,R=6378*1000m,则haversine公式可写为:
import numpy as np
def haversine(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
return c * 6367 * 1000