Measure distance between two cities in Python

Jiradett  Kerdsri
1 min readNov 22, 2019

--

To find the distance between two locations on earth, I did tried both Geopy package in Python and GoogleMap API. But, none of them works really well, I got a lot of ‘Timeout’ issue with free Geopy and you have to pay for Google API service. After serveral attemps, here is what I did:

  • First, convert the city name to lat and long using Opencage API.
pip install opencage
  • You’ll have to get an API key first, then use this code.
from opencage.geocoder import OpenCageGeocode
key = ‘YourAPIkey’ # get api key from: https://opencagedata.com
geocoder = OpenCageGeocode(key)query = ‘Los Angeles CA’
results = geocoder.geocode(query)
lat = results[0][‘geometry’][‘lat’]lng = results[0][‘geometry’][‘lng’]print (lat, lng)
  • After that, I can find the distance from lat and long with geopy.distance
pip install geopyp
  • Finally, I use this code:
def find_distance(A,B):
key = 'YourAPIkey' # get api key from: https://opencagedata.com
geocoder = OpenCageGeocode(key)

result_A = geocoder.geocode(A)
lat_A = result_A[0]['geometry']['lat']
lng_A = result_A[0]['geometry']['lng']

result_B = geocoder.geocode(B)
lat_B = result_B[0]['geometry']['lat']
lng_B = result_B[0]['geometry']['lng']

return (geodesic((lat_A,lng_A), (lat_B,lng_B)).kilometers)

--

--

No responses yet