Calculate distance and duration between two places using google distance matrix API in Python?

We almost all use google maps to check distance between source and destination and check the travel time. For developers and enthusiasts, google provide ‘google distance matrix API’ to calculate the distance and duration between two places.

To use google distance matrix api, we need google maps API keys, which you can get from below link:

Required libraries

We can accomplish this by using different python library, like:

  • Pandas
  • googlemaps
  • Requests
  • Json

I am using very basic requests and json library. Using pandas you can fill multiple source and destination places at a time and get the result in csv file.

Below is the program to implement the same:

# Import required library
import requests
import json
#Enter your source and destination city
originPoint = input("Please enter your origin city: ")
destinationPoint= input("Please enter your destination city: ")
#Place your google map API_KEY to a variable
apiKey = 'YOUR_API_KEY'
#Store google maps api url in a variable
url = ''
# call get method of request module and store respose object
r = requests.get(url + 'origins = ' + originPoint + '&destinations = ' + destinationPoint + '&key = ' + apiKey)
#Get json format result from the above response object
res = r.json()
#print the value of res


Please enter your origin city: Delhi
Please enter your destination city: Karnataka
{'destination_addresses': [‘Karnataka, India’],'origin_addresses': [‘Delhi, India’], 'rows': [{'elements': [{'distance': {'text': '1,942 km', 'value': 1941907}, 'duration': {'text': '1 day 9 hours', 'value': 120420},
'status': 'OK'}]}], 'status': 'OK'}