How to calculate distance from different markers in a map and then pick up the least one

后端 未结 9 1032
野趣味
野趣味 2020-12-05 08:53

I have to get distance from different markers on the map to the current location of the device and the pick up the shortest one. I have the lat and long for the markers and

9条回答
  •  被撕碎了的回忆
    2020-12-05 09:35

    If you want to find the shortest one not list the closest and you want the process to scale to a large amount of locations, you can do some filtering before you calculate distances and you can simplify the formula to speed it up as you don't care about actual distances (i.e. remove the multiplication by the radius of the earth).

    Filtering algorithm, looping through each location :

    1. Calculate the difference in lat and long.
    2. If both differences are larger then a previously processed pair, discard it.
    3. Calculate distance, keep smallest.

    You can further help the algorithm by feeding it with what might be close locations first. For example if you know one of the points is in the same country or state.


    Here is some Python code to do that, use it as pseudocode for your solution :

    locations = { 
        'Bangalore' : (12.971599, 77.594563), 
        'Delhi' : (28.635308,  77.224960), 
        'Mumbai' : (19.075984,  72.877656), 
        'Chennai' : (13.052414,  80.250825), 
        'Kolkata' : (22.572646,  88.363895)
        }
    
    from math import sin, cos, atan2, sqrt
    
    EARTH_RADIUS = 6373  # km
    
    def distance(a, b):  # pass tuples
        (lat1, lon1) = a
        (lat2, lon2) = b
        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) ) 
        return EARTH_RADIUS * c
    
    
    current = (17.385044, 78.486671)  # current lat & lng
    
    closest = None
    closest_name = None
    for name, cordinates in locations.iteritems():
        d = distance(current, cordinates)
        if closest is None or d < closest:
            closest = d
            closest_name = name
        print "~%dkm (%s)" % (distance(current, cordinates), name)
    
    print "\nClosest location is %s, %d km away." % (closest_name, closest)
    

    Output :

    ~5700km (Kolkata)
    ~13219km (Chennai)
    ~12159km (Bangalore)
    ~7928km (Delhi)
    ~10921km (Mumbai)
    
    Closest location is Kolkata, 5700 km away.
    

提交回复
热议问题