我的坐标如下所示
lat=9.0516854
longi= 76.5360752
我需要做的是,从具有ID的位置集中找到最近的经度和纬度。 就像
{8: [{'id': 8, 'latitude': '9.042418900000001', 'longitude': '76.5861815'}], 9: [{'id': 9, 'latitude': '34.1047016', 'longitude': '-118.3338668'}], 10: [{'id': 10, 'latitude': '8.5469144', 'longitude': '76.8792397'}]}
谁能帮助我,谢谢你
答案 0 :(得分:2)
要正确计算地球上各点之间的距离,需要使用Haversine公式。使用Python,您可以这样编码:
from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
return 12742 * asin(sqrt(a))
lat=9.0516854
longi= 76.5360752
base_cordinate = {'lat': lat, 'lon': longi}
d = {8: [{'id': 8, 'latitude': '9.042418900000001', 'longitude': '76.5861815'}], 9: [{'id': 9, 'latitude': '34.1047016', 'longitude': '-118.3338668'}], 10: [{'id': 10, 'latitude': '8.5469144', 'longitude': '76.8792397'}]}
def closest(data, v):
return min(data, key=lambda p: distance(v['lat'],v['lon'],p['lat'],p['lon']))
cord_list = []
for k,v in d.items():
new_lat = float(v[0]['latitude'])
new_long = float(v[0]['longitude'])
cord_dict = {'lat' : new_lat, 'lon' : new_long}
cord_list.append(cord_dict)
closest_cordinate = closest(cord_list, base_cordinate)
# To Get the id
def fetch_id(base_dict, closest):
for key, val in d.items():
if float(val[0]['latitude']) == closest_cordinate['lat'] and float(val[0]['longitude']) == closest_cordinate['lon']:
return val[0]['id']
closest_cordinate['id'] = fetch_id(d, closest_cordinate)
print(closest_cordinate)