Python | Calculate distance and duration between two places using google distance matrix API
Google Map Distance Matrix API is a service that provides travel distance and time taken to reach destination. This API returns the recommended route(not detailed) between origin and destination, consists of duration and distance values for each pair.
To use this API, one must need the API key, which can be get form here.
Modules needed :
import requests
import json
Below is the implementation :
# importing required libraries import requests, json # enter your api key here api_key ='Your_api_key' # Take source as input source = input() # Take destination as input dest = input() # url variable store url # Get method of requests module # return response object r = requests.get(url + 'origins = ' + source + '&destinations; = ' + dest + '&key; = ' + api_key) # json method of response object # return json format result x = r.json() # bydefault driving mode considered # print the vale of x print(x) |
Output :
dehradun
haridwar
{'destination_addresses': ['Haridwar, Uttarakhand, India'],
'origin_addresses': ['Dehradun, Uttarakhand, India'], 'rows':
[{'elements': [{'distance': {'text': '56.3 km', 'value': 56288},
'duration': {'text': '1 hour 40 mins', 'value': 5993},
'status': 'OK'}]}], 'status': 'OK'}
Using googlemaps module :
Distance between two places can also be calculated using googlemaps module.
Command to install googlemaps module :
pip install googlemaps
# importing googlemaps module import googlemaps # Requires API key gmaps = googlemaps.Client(key='Your_API_key') # Requires cities name my_dist = gmaps.distance_matrix('Delhi','Mumbai')['rows'][0]['elements'][0] # Printing the result print(my_dist) |
Output :
{'distance': {'text': '1,415 km', 'value': 1415380}, 'duration': {'text': '23 hours 42 mins', 'value': 85306}, 'status': 'OK'}
Thanks to aishwarya.27 for contributing this method.
Recommended Posts:
- Python PIL | BoxBlur() method
- Python | sympy.ones() method
- Python | sympy.zeros() method
- Python | sympy.eye() method
- How to write an empty function in Python - pass statement?
- Operator Functions in Python | Set 2
- Rearrange a string so that all same characters become d distance away
- Time Functions in Python | Set-2 (Date Manipulations)
- Send mail from your Gmail account using Python
- Python – The new generation Language
- Print Single and Multiple variable in Python
- Increment and Decrement Operators in Python
- str() vs repr() in Python
- Swap two variables in one line in C/C++, Python, PHP and Java
- Generate all permutation of a set in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



