Google Map Distance Matrix API is a service that provides travel distance and time is taken to reach a destination. This API returns the recommended route(not detailed) between origin and destination, which 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 :
Below is the implementation :
Python3
# 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() # by default driving mode considered # print the value 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
- The first step is to import the googlemaps module. This module is used to access the Google Maps API from within Python.
- Next, an API key is required to access the Google Maps API. The API key is passed as a parameter to the Client constructor.
- Once the client is set up, the next step is to specify the cities for which you want to obtain distance data. In this example, the cities specified are Delhi and Mumbai. The distance_matrix function is called with the two city names as parameters.
The distance_matrix function returns a dictionary with information about the distance between the two cities. The [‘rows’][0][‘elements’][0] syntax is used to extract the distance value from the dictionary. - Finally, the result is printed using the print function.
Python3
# 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.