给定一个JSON文件,
{"BusStopCode": "00481", "RoadName": "Woodlands Rd", "Description": "BT PANJANG TEMP BUS PK", "Latitude": 1.383764, "Longitude": 103.7583},
{"BusStopCode": "01012", "RoadName": "Victoria St", "Description": "Hotel Grand Pacific", "Latitude": 1.29684825487647, "Longitude": 103.85253591654006}
在众多的公交站中,我试图根据这个包含5000个公交站的列表以及任何用户给定的经纬度使用给定的公式找到最近的公交站。
import math
R = 6371000 #radius of the Earth in m
x = (lon2 - lon1) * cos(0.5*(lat2+lat1))
y = (lat2 - lat1)
d = R * sqrt( x*x + y*y )
我的问题是,针对用户输入的lat1和lon1,如何计算lat1 lon1与所有5000个json文件中的lat2 lon2之间的所有距离,并打印出最低的5个距离?我考虑使用list.sort,但不确定如何使用python计算所有5000个距离。非常感谢。
编辑:
根据Eric Duminil的代码,以下代码适用于我的需求。
from math import cos, sqrt
import sys
import json
busstops = json.loads(open("stops.json").read())
R = 6371000 #radius of the Earth in m
def distance(lon1, lat1, lon2, lat2):
x = (lon2-lon1) * cos(0.5*(lat2+lat1))
y = (lat2-lat1)
return R * sqrt( x*x + y*y )
buslist = sorted(busstops, key= lambda d: distance(d["Longitude"], d["Latitude"], 103.5, 1.2))
print(buslist[:5])
输入的经度和纬度示例为 103.5, 1.2,来自 buslist。