
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Distance and Duration 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 = 'https://maps.googleapis.com/maps/api/distancematrix/json?' # 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 print(res)
Output
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'}
Advertisements