abhi krishnan
abhi krishnan

Reputation: 836

How to find Shortest distance of a location from a route (Python),

I am having a coordinate as given below

lat=9.0516854 
longi= 76.5360752

what I need to do is, to find the nearest latitude and longitude from a set of location with an id. which is exactly like

{8: [{'id': 8, 'latitude': '9.042418900000001', 'longitude': '76.5861815'}], 9: [{'id': 9, 'latitude': '34.1047016', 'longitude': '-118.3338668'}], 10: [{'id': 10, 'latitude': '8.5469144', 'longitude': '76.8792397'}]}

Can anyone help me, ThankYou

Upvotes: 2

Views: 1323

Answers (1)

Sreeram TP
Sreeram TP

Reputation: 11927

For a correct calculation of the distance between points on the globe, you need something like the Haversine formula. Using Python 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))

lat=9.0516854 
longi= 76.5360752

base_cordinate = {'lat': lat, 'lon': longi}

d = {8: [{'id': 8, 'latitude': '9.042418900000001', 'longitude': '76.5861815'}], 9: [{'id': 9, 'latitude': '34.1047016', 'longitude': '-118.3338668'}], 10: [{'id': 10, 'latitude': '8.5469144', 'longitude': '76.8792397'}]}

def closest(data, v):
    return min(data, key=lambda p: distance(v['lat'],v['lon'],p['lat'],p['lon']))

cord_list = []

for k,v in d.items():

    new_lat = float(v[0]['latitude'])
    new_long = float(v[0]['longitude'])

    cord_dict = {'lat' : new_lat, 'lon' : new_long}
    cord_list.append(cord_dict)

closest_cordinate = closest(cord_list, base_cordinate)

# To Get the id

def fetch_id(base_dict, closest):

    for key, val in d.items():

        if float(val[0]['latitude']) == closest_cordinate['lat'] and float(val[0]['longitude']) == closest_cordinate['lon']:
            return val[0]['id']

closest_cordinate['id'] = fetch_id(d, closest_cordinate)

print(closest_cordinate)

Upvotes: 3

Related Questions