Calculating Distance Between Two Geo Points In Python

As you may be aware, I am a Python tutor online and quite often I get asked pretty specific questions. This week, I was asked to show a simple way to find the distance in kilometres between two geographic locations.

So, here it is then – the easiest way to approach this problem is to use the geopy library. I then, define a list of locations I want to check in a dictionary, which includes the latitude, longitude data for each landmark.

The goal of the script is to determine the distance each of these landmarks is away from the London Eye.

We simply loop through the dictionary and extract the latitude and longitudes. We put them into a lat,long tuple.

We then plug the lat long of the location we are checking along with the lat long of the London Eye into the geodesic function : geodesic(lat_long, london_eye).

And that is really it. We take two lat long pairs and use the geopy library to tell us the distance between them.

from geopy.distance import geodesic

destinations = { 'bigben' : {'latitude': 51.510357,
                            'longitude': -0.116773},
                 'heathrow' : {'latitude': 51.470020,
                            'longitude': -0.454295},
                 'alton_towers' : {'latitude': 52.987662716,
                            'longitude': -1.888829778}

for key, value in destinations.items():
    lat_long =  (value['latitude'], value['longitude'])
    location = key
    london_eye = 51.503399, -0.119519

    print(key + ' is ' + str(round(geodesic(lat_long, london_eye).kilometers,2)) + 'KM from the London Eye')