给定一个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}
,以此类推。。在
根据给定的每个公共汽车站的lat/5000,用户可以根据给定的公式找到最近的公共汽车站
^{pr2}$我的问题是,对于用户输入的lat1和lon1,如何计算lat1 lon1和lat2 lon2之间的所有距离(其中lat2 lon2将取json文件中所有5000 lat/lon的值),然后打印最低的5个距离?在
我想用列表.排序但我不确定我是如何使用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 from buslist是一个用户输入经度纬度的示例。在
您可以简单地定义一个函数来计算距离,并使用^{} 参数对公共汽车站进行排序:
一旦这个列表被排序,您可以简单地用
[:5]
提取最近的5个公共汽车站。 它应该足够快,即使有5000个公共汽车站。在请注意,如果您不关心具体的距离,而只想对公共汽车站进行排序,则可以使用此函数作为键:
^{pr2}$对于这样一个项目,我也做了同样的工作,但是计算一个大型数据集的所有距离可能需要很多时间。在
最后我得到了knn nearest neighbors,它更快,而且不需要一直重新计算距离:
之后,我用这些数据用networkx构建了一个图形,但我仍然使用knn.kneighbors公司(userlocation)查找用户最近的点。在
相关问题 更多 >
编程相关推荐