Calculate distance from one point to all others

前端 未结 3 536
予麋鹿
予麋鹿 2021-01-15 09:34

I am working with a list of ID, X, and Y data for fire hydrant locations. I am trying to find the three closest fire hydrants for each fire hydrant in the list.

a =

3条回答
  •  一整个雨季
    2021-01-15 10:26

    If you have geolocation, we can perform simple distance calculation(https://en.m.wikipedia.org/wiki/Haversine_formula) to get kilometers distance between two locations. This code is NOT meant to be efficient. If this is what you want we can use numpy to speed it up:

    import math
    
    def distance(lat,lon, lat2,lon2):
    
        R = 6372.8  # Earth radius in kilometers
    
        # change lat and lon to radians to find diff
    
        rlat = math.radians(lat)
        rlat2 = math.radians(lat2)
        rlon = math.radians(lon)
        rlon2 = math.radians(lon2)
    
        dlat = math.radians(lat2 - lat)
        dlon = math.radians(lon2 - lon)
    
    
        m = math.sin(dlat/2)**2 + \
            math.cos(rlat)*math.cos(rlat2)*math.sin(dlon/2)**2
    
        return 2 * R * math.atan2(math.sqrt(m),
                                   math.sqrt(1 - m))
    
    a = [['ID1', 52.5170365, 13.3888599],
         ['ID2', 54.5890365, 12.5865499],
         ['ID3', 50.5170365, 10.3888599],
        ]
    
    b = []  
    for id, lat, lon in a:
        for id2, lat2, lon2 in a:
            if id != id2:
                d = distance(lat,lon,lat2,lon2)
                b.append([id,id2,d])
    
    print(b)
    

提交回复
热议问题