给定一个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 和 lat2 lon2 之间的所有距离(其中 lat2 lon2 将采用 json 文件中所有 5000 lat/lon 的值),然后打印最低的 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])
其中来自 buslist 的 103.5、1.2 是用户输入经度纬度的示例。
最佳答案
您可以简单地定义一个函数来计算距离,并使用它来通过 key
对公交车站进行排序参数:
from math import cos, sqrt, pi
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 (2*pi*R/360) * sqrt( x*x + y*y )
bustops = [{"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}]
print(sorted(bustops, key= lambda d: distance(d["Longitude"], d["Latitude"], 103.5, 1.2)))
# [{'BusStopCode': '01012', 'RoadName': 'Victoria St', 'Description': 'Hotel Grand Pacific', 'Latitude': 1.29684825487647, 'Longitude': 103.85253591654006}, {'BusStopCode': '00481', 'RoadName': 'Woodlands Rd', 'Description': 'BT PANJANG TEMP BUS PK', 'Latitude': 1.383764, 'Longitude': 103.7583}]
此列表排序后,您可以使用 [:5]
简单地提取最近的 5 个公交车站。
它应该足够快,即使有 5000 个公交车站。
注意,如果你不关心具体的距离,只想对公交站点进行排序,可以使用这个函数作为key:
def distance2(lon1, lat1, lon2, lat2):
x = (lon2 - lon1) * cos(0.5*(lat2+lat1))
y = (lat2 - lat1)
return x*x + y*y
关于python - 给定经纬度,根据经纬度的 json 列表找到最近的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641706/