对于像我这样通过搜索引擎来到这里的人,以及正在寻找开箱即用的解决方案的人,我建议安装mpu。通过pip Install mpu——user安装它,然后像这样使用它来获得haversine距离:
import mpu
# Point one
lat1 = 52.2296756
lon1 = 21.0122287
# Point two
lat2 = 52.406374
lon2 = 16.9251681
# What you were looking for
dist = mpu.haversine_distance((lat1, lon1), (lat2, lon2))
print(dist) # gives 278.45817507541943.
另一个包是gpxpy。
如果你不想要依赖,你可以使用:
import math
def distance(origin, destination):
"""
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
--------
>>> origin = (48.1372, 11.5756) # Munich
>>> destination = (52.5186, 13.4083) # Berlin
>>> round(distance(origin, destination), 1)
504.2
"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
math.sin(dlon / 2) * math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius * c
return d
if __name__ == '__main__':
import doctest
doctest.testmod()
另一种替代方案是haversine:
from haversine import haversine, Unit
lyon = (45.7597, 4.8422) # (latitude, longitude)
paris = (48.8567, 2.3508)
haversine(lyon, paris)
>> 392.2172595594006 # In kilometers
haversine(lyon, paris, unit=Unit.MILES)
>> 243.71201856934454 # In miles
# You can also use the string abbreviation for units:
haversine(lyon, paris, unit='mi')
>> 243.71201856934454 # In miles
haversine(lyon, paris, unit=Unit.NAUTICAL_MILES)
>> 211.78037755311516 # In nautical miles
他们声称对两个向量中所有点之间的距离进行了性能优化:
from haversine import haversine_vector, Unit
lyon = (45.7597, 4.8422) # (latitude, longitude)
paris = (48.8567, 2.3508)
new_york = (40.7033962, -74.2351462)
haversine_vector([lyon, lyon], [paris, new_york], Unit.KILOMETERS)
>> array([ 392.21725956, 6163.43638211])