我如何找到最近的地方 Python 和 Google 地图 API
How would I find the closest place Python and the Google Maps API
我有这个程序,我希望它 return 列表中的几个位置,顺序最接近经度和纬度的设定点。我希望它 return,例如,在我的 longs 和 lats 元组列表中的五个最近的位置,按顺序,到设定点。我用 Python.
做这个
使用:Haversine,你可以这样做:
from math import radians, cos, sin, asin, sqrt
center = (lon, lat)
points = [(lon1, lat1), (lon2, lat2), (lon3, lat3), (lon4, lat4), (lon5, lat5))
altogether = [list(center) + list(item) for item in points]
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
distances = list(map(lambda a: haversine(*a), altogether))
我有这个程序,我希望它 return 列表中的几个位置,顺序最接近经度和纬度的设定点。我希望它 return,例如,在我的 longs 和 lats 元组列表中的五个最近的位置,按顺序,到设定点。我用 Python.
做这个使用:Haversine,你可以这样做:
from math import radians, cos, sin, asin, sqrt
center = (lon, lat)
points = [(lon1, lat1), (lon2, lat2), (lon3, lat3), (lon4, lat4), (lon5, lat5))
altogether = [list(center) + list(item) for item in points]
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
distances = list(map(lambda a: haversine(*a), altogether))