2017-10-09 61 views
3

给出一个JSON文件的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个距离。

非常感谢。

编辑

与埃里克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是示例用户输入经度纬度。

+0

只是检查出https://pypi.python.org /的PyPI/geopy。你可能会找到一种方法来获得某种方式。另请查看此评论https://stackoverflow.com/a/19412565/6165783 –

+0

谢谢你的链接。然而,我并不关心2 lat/lon之间距离的计算,而是 - 用户给出纬度/经度,我怎样才能找到最近的5个公交站点,并且有一个5000个巴士站的json文件。 –

+0

道歉,如果我的问题不好措辞 –

回答

2

你可以简单地定义一个函数来计算距离,并用它来进行排序与​​key参数巴士站:

from math import cos, sqrt 

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) 

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个巴士站。

需要注意的是,如果你不关心具体的距离,而是只想排序公交车站,你可以使用这个功能键:

def distance2(lon1, lat1, lon2, lat2): 
    x = (lon2 - lon1) * cos(0.5*(lat2+lat1)) 
    y = (lat2 - lat1) 
    return x*x + y*y 
+0

谢谢,这正是我需要的。然而,当我尝试[:5]时,我有以下错误:'NoneType'对象不是可订阅的 –

+0

已更改代码并工作(请参阅问题文章) –