找到最近的值对 w/ Python3

Find Nearest Value Pair w/ Python3

我的目标是检索用户的 lat/long 位置,然后在我的位置列表中找到最近的 lat/long。以下是我所拥有的,我相信它有效,但我不确定这是否是获得我想要的最终结果的最佳方法。

我浏览位置列表,将它们转换为绝对值,然后减去用户的位置值以获得距离。如果 X 和 Y 小于先前记录的 X 或 Y,则距离变量将更新为新值。

这似乎有效,但是,就像我说的,我不确定我是否以最好的方式进行了处理。我的位置列表会经常更新,但不会超过 100 个可能的位置。

非常感谢您的宝贵时间。

locations = [(-71.43994800000002,41.6919549),
(-71.61075089999997,41.577545),
(-71.06653670000003,42.41383099999999),
(-71.41283429999999,41.8239891),
(-71.05888010000001,42.3600825),
(-74.00594130000002,40.7127837)]

userlocation = (-71.28254930000003,41.7303793)

distance = [999,999] #initial value holder for distance
for location in locations:
    x = abs(location[0]) # absolute value of latitude
    y = abs(location[1]) #absolute value of longitude
    xu = abs(userlocation[0]) #absolute value of user's latitude
    yu = abs(userlocation[1]) #absolute value of user's longitude
    dx = x-xu #Subtract user from location X
    dy = y-yu #subtract user from location Y
    if dx < distance[0]: #if distance X is less than the current distance value
        distance[0] = dx #update with new values
        distance[1] = dy
        continue #go to the next one
    if dy < distance[1]: #if distance Y is less than the current distance value
        distance[0] = dx #update with new values
        distance[1] = dy
        continue #go to the next one
print(distance) #print the end smallest result

我会尝试获取真实距离,然后以一种骇人听闻的方式比较距离 Calculate distance between two latitude-longitude points? (Haversine formula),然后

def calculate_distance(lat1, lon1, lat2, lon2):
   # go to the link to use the implementation
   pass
locations = []
user_loc = (-71.28254930000003,41.7303793)
ulat, ulon = user_loc
res = map(lambda x: (calculate_distance(ulat, ulon, x[0], x[1]), x), locations)
print min(res, key=lambda x: x[0])