我有一个程序可以将纬度/经度的用户输入与一组纬度/经度进行比较,并显示最接近的代码。下面的代码可以正常工作:

#prints out the closest lat and lon
from math import cos, asin, sqrt

#Haversine formula
def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295#degree to radian
    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
    return 12742 * asin(sqrt(a))#print in km


def closest(data, v):
    return min(data, key=lambda p:   distance(v['lat'],v['lon'],p['lat'],p['lon']))

sdata = [{'lat': 37.82, 'lon': 86.142},
        {'lat': 38.88,  'lon': 87.251 },
        {'lat': 39.78, 'lon': 89.336},
        {'lat': 40.42, 'lon': 86.123},
        {'lat': 41.35,  'lon': 90.21 },
        {'lat': 39.66, 'lon': 87.11}]

lat = input("Latitude:")
lon = input("Longitude:")

cust = {'lat': lat, 'lon':lon}

print(closest(sdata,cust))


但是我想在一个范围内显示结果,即从列表中最接近/最远的纬度/经度,而不是单个纬度/经度输出。
输入:lat:40 lon:80
输出:{'lat': 40.42, 'lon': 86.123}
预期输出:{'lat': 40.42, 'lon': 86.123}, {'lat': 39.78, 'lon': 89.336}, {'lat': 39.66, 'lon': 87.11},{'lat': 41.35, 'lon': 90.21 },{'lat': 38.88, 'lon': 87.251 },{'lat': 37.82, 'lon': 86.142}

最佳答案

获取输入的所有距离的列表,然后对其进行排序
在Python 3中测试

from operator import itemgetter

# Use raw_input() with Python 2
lat = float(input("Latitude:"))
lon = float(input("Longitude:"))

distances = (distance(v['lat'],v['lon'],lat,lon) for v in sdata)
for lat_lng, d in sorted(zip(sdata, distances), key=itemgetter(1)):
  print(lat_lng['lat'], lat_lng['lon'], d)

输出量
Latitude: 0.0
Longitude: 0.0

37.82 86.142 9668.762962674926
40.42 86.123 9679.445101487952
39.66 87.11 9760.193791714297
38.88 87.251 9769.623036766754
39.78 89.336 9950.802415333788
41.35 90.21 10025.072644640604

关于python - 比较纬度/经度并在Python中显示最接近,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49043009/

10-12 22:00