python - 给定经纬度,根据经纬度的 json 列表找到最近的位置

标签 python json python-3.x

给定一个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/

相关文章:

python - 如何只允许 getter/setter 获取/设置变量值?

python - 神秘时间转换( Pandas 和日期时间)

python - 如果您不知道有多少数据通过,如何接收套接字信息?

java - python和java继承差异概述

python - 将两个 JSON 对象合并为一个

Python 3 Tkinter - 更改具有相同名称的多个条目的状态

python - 如何加入列表中的某些项目

json - Laravel 4 和 Mandrill JSON 响应

java - Gson如何将json转换为自定义类

python - 分组列和计算