【发布时间】:2018-03-20 09:11:48
【问题描述】:
给定一个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])
其中 103.5, 1.2 from buslist 是用户输入经度纬度的示例。
【问题讨论】:
-
看看pypi.python.org/pypi/geopy。你可能会找到一种方法来获得某种方式。另请查看此评论stackoverflow.com/a/19412565/6165783
-
感谢您的链接。但是,我并不关心 2 lat/lon 之间距离的计算,而是 - 对于给定 lat/lon 的用户,我如何使用包含 5000 个公交车站的 json 文件找到最近的 5 个公交车站。
-
抱歉,如果我的问题表述不好
标签: python json python-3.x