简体   繁体   中英

Finding the minimal distance between two coordinates from different lists

Sorry in advance, currently on mobile!

So I basically have one list with around 50,000 lat/long tuples (list 1) and another one with around 1,800 lat/long tuples (list 2).

What I want to do is the following: For each of the list elements in list 1, I want to I want to find the closest point out of the list elements in list 2, so that I basically end up with a list of around 50,000 values that represent the minimal distances.

I did not have any issues in calculating the distance for single elements using geopy.distance, however, I am stuck with the for loop implementation and appreciate any help!

Thanks a lot.

from math import sin, cos, sqrt, atan2

def distanceCheck(lat1, lat2, lon1, lon2):
    R = 6373.0
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = (sin(dlat/2))**2 + cos(lat1) * cos(lat2) * (sin(dlon/2))**2
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    distance = R * c
    return distance

distarr = []
for p1 in list1:
    minDist = None
    point = None
    for p2 in list2:
        #DISTANCE CHECK HERE - 
        check = distanceCheck(p1.lat, p2.lat, p1.lon, p2.lon)
        if not minDist:
            minDist = check
            point = p2
        else:
            if check < minDist:
                minDist = check
                point = p2
    distarr.append({'min': minDist, 'to': point, 'from': p1})
    
print("{}".format(distarr))

list1 and list2 are the lists with lat and lon. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM