查找距离点最近的坐标
问题描述
我有城市坐标:(52.2319581, 21.0067249)
和Python字典,上面提到的城市周围有城市。如何从给定的坐标中获取最近的3个城市:
({'Brwinów': (52.133333, 20.716667), 'Warszawa Bielany': (52.283333, 20.966667), 'Legionowo': (52.4, 20.966667), 'Warszawa-Okęcie': (52.16039, 20.961674), 'Warszawa': (52.280957, 20.961348), 'Belsk Duży': (51.833333, 20.8)}, {})
感谢您的帮助。
解决方案
不带任何外部库
from math import acos, cos, sin
def gc_distance(first_point, second_point):
return acos(sin(first_point[1]) * sin(second_point[1]) + cos(first_point[1]) * cos(second_point[1]) * cos(first_point[0] - second_point[0]))
def three_closest(city, cities):
cities_distances = { key: gc_distance(city, value) for key, value in cities.items()}
return [k for k, v in sorted(cities_distances.items(), key=lambda item: item[1])][:3]
样本测试:
>>> city = (52.2319581, 21.0067249)
>>> cities = {'Brwinów': (52.133333, 20.716667), 'Warszawa Bielany': (52.283333, 20.966667), 'Legionowo': (52.4, 20.966667), 'Warszawa-Okęcie': (52.16039, 20.961674), 'Warszawa': (52.280957, 20.961348), 'Belsk Duży': (51.833333, 20.8)}
>>> three_closest(city, cities)
['Warszawa Bielany', 'Warszawa', 'Warszawa-Okęcie']
如果要返回键和值,请执行以下操作:
for result in three_closest(city, cities):
print(result + " : " + str(cities[result]))
获取:
Warszawa Bielany : (52.283333, 20.966667)
Warszawa : (52.280957, 20.961348)
Warszawa-Okęcie : (52.16039, 20.961674)
相关文章