Find the closest latitude and longitude

前端 未结 3 1652
情深已故
情深已故 2020-12-08 03:05

I\'m writing a small program and to improve efficiency, I need to be able to find the closest latitude and longitude in my array.

Assume you have the following code:

相关标签:
3条回答
  • 2020-12-08 03:51

    Also u can simple do:

    import mpu
    def distance(point1, point2):
        return mpu.haversine_distance(point1, point2)
    
    def closest(data, this_point):
        return min(data, key=lambda x: distance(this_point, x))
    
    0 讨论(0)
  • 2020-12-08 03:53

    For a correct calculation of the distance between points on the globe, you need something like the Haversine formula. Using the Python implementation offered in this answer, you could code it like this:

    from math import cos, asin, sqrt
    
    def distance(lat1, lon1, lat2, lon2):
        p = 0.017453292519943295
        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))
    
    def closest(data, v):
        return min(data, key=lambda p: distance(v['lat'],v['lon'],p['lat'],p['lon']))
    
    tempDataList = [{'lat': 39.7612992, 'lon': -86.1519681}, 
                    {'lat': 39.762241,  'lon': -86.158436 }, 
                    {'lat': 39.7622292, 'lon': -86.1578917}]
    
    v = {'lat': 39.7622290, 'lon': -86.1519750}
    print(closest(tempDataList, v))
    
    0 讨论(0)
  • 2020-12-08 04:07

    if earth is plane,

    from itertools import combinations
    from math import sqrt
    
    coords = [{'lat': 39.7612992 , 'lon': -86.1519681}, 
                    {"lat": 39.762241, "lon": -86.158436}, 
                    {"lat": 39.7622292, "lon": -86.1578917}]
    
    
    def euclidean(l1, l2):
        return ((l1[0]**2)-(l2[0]**2)) + ((l1[1]**2)-(l2[1]**2)) 
    
    pairs = [j for j in combinations([i.values() for i in coords], 2)]
    pairs.sort(key= lambda x: euclidean(*x))
    print pairs[-1]
    
    0 讨论(0)
提交回复
热议问题