我使用gmail地理编码功能获得经度和纬度。现在我需要计算2点之间的距离。我找到了Haversine公式并且效果很好,但是在google js api中我在Geometry Library中找到了computeDistanceBetween(lat,lng)方法。我的问题是python的函数或库?
答案 0 :(得分:4)
from math import *
def greatCircleDistance((lat1, lon1), (lat2, lon2)):
def haversin(x):
return sin(x/2)**2
return 2 * asin(sqrt(
haversin(lat2-lat1) +
cos(lat1) * cos(lat2) * haversin(lon2-lon1)))
返回球体上各点之间的角距离。要获得长度(公里)的距离,请将结果乘以地球半径。
但你也可以在公式集合中查找它,因此有一堆downvotes; - )
答案 1 :(得分:2)
您可以使用Google Maps API计算两点之间的距离。
查找两个城市之间的距离:
import googlemaps
# Requires API key
gmaps = googlemaps.Client(key='Your_API_key')
# Requires cities name
distance = gmaps.distance_matrix('Delhi','Mumbai')['rows'][0]['elements'][0]
print(distance)
{u'distance': {u'text': u'1,418 km', u'value': 1417632},
u'duration': {u'text': u'1 day 0 hours', u'value': 87010},
u'status': u'OK'}
如果您具有起点和终点的地理坐标(纬度和经度),请执行以下操作:
# Requires geo-coordinates(latitude/longitude) of origin and destination
origin_latitude = 12.9551779
origin_longitude = 77.6910334
destination_latitude = 28.505278
destination_longitude = 77.327774
distance = gmaps.distance_matrix([str(origin_latitude) + " " + str(origin_longitude)], [str(destination_latitude) + " " + str(destination_longitude)], mode='walking')['rows'][0]['elements'][0]
print(distance)
{u'distance': {u'text': u'2,014 km', u'value': 2013656},
u'duration': {u'text': u'16 days 23 hours', u'value': 1464529},
u'status': u'OK'}
答案 2 :(得分:2)
使用geopy https://pypi.org/project/geopy/
In [39]: from geopy.distance import geodesic
In [40]: you = ("73.6490763,-43.9762069")
In [41]: me = ("73.646628,-43.970497")
In [42]: miles = geodesic(me,you).miles
In [43]: f"Miles: {miles:.2f}"
Out[43]: 'Miles: 0.20'