Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 provides the Google Distance Matrix API to calculate the distance and duration between two places programmatically.
To use Google Distance Matrix API, we need Google Maps API keys, which you can get from the official documentation:
https://developers.google.com/maps/documentation/distance-matrix/get-api-key
Required Libraries
We can accomplish this by using different Python libraries:
- requests − For making HTTP API calls
- json − For parsing JSON responses
- googlemaps − Official Google Maps client (optional)
- pandas − For handling multiple locations and CSV export (optional)
In this tutorial, we'll use the basic requests and json libraries to interact with the API.
Basic Implementation
Here's a simple program to calculate distance and duration between two cities ?
import requests
import json
# Enter your source and destination city
origin_point = "Delhi"
destination_point = "Mumbai"
# Replace with your actual Google Maps API key
api_key = 'YOUR_API_KEY'
# Google Maps Distance Matrix API URL
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
# Build the complete API request URL
params = {
'origins': origin_point,
'destinations': destination_point,
'key': api_key
}
# Make API request
response = requests.get(url, params=params)
# Get JSON format result
result = response.json()
# Print the complete response
print("Complete API Response:")
print(json.dumps(result, indent=2))
Extracting Specific Information
The API response contains nested data. Here's how to extract specific distance and duration information ?
import requests
import json
def get_distance_duration(origin, destination, api_key):
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
params = {
'origins': origin,
'destinations': destination,
'key': api_key,
'units': 'metric' # Use metric units
}
response = requests.get(url, params=params)
result = response.json()
# Check if request was successful
if result['status'] == 'OK':
element = result['rows'][0]['elements'][0]
if element['status'] == 'OK':
distance = element['distance']['text']
duration = element['duration']['text']
return {
'origin': result['origin_addresses'][0],
'destination': result['destination_addresses'][0],
'distance': distance,
'duration': duration
}
else:
return {'error': f"Route not found: {element['status']}"}
else:
return {'error': f"API request failed: {result['status']}"}
# Example usage
api_key = 'YOUR_API_KEY'
origin = 'Delhi, India'
destination = 'Mumbai, India'
result = get_distance_duration(origin, destination, api_key)
print("Travel Information:")
for key, value in result.items():
print(f"{key.title()}: {value}")
Sample Output
Travel Information: Origin: Delhi, India Destination: Mumbai, Maharashtra, India Distance: 1,411 km Duration: 14 hours 12 mins
Handling Multiple Destinations
You can also calculate distances to multiple destinations from a single origin ?
import requests
import json
def get_multiple_distances(origin, destinations, api_key):
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'
# Join multiple destinations with pipe separator
destinations_str = '|'.join(destinations)
params = {
'origins': origin,
'destinations': destinations_str,
'key': api_key,
'units': 'metric'
}
response = requests.get(url, params=params)
result = response.json()
if result['status'] == 'OK':
origin_addr = result['origin_addresses'][0]
destinations_addr = result['destination_addresses']
elements = result['rows'][0]['elements']
travel_data = []
for i, element in enumerate(elements):
if element['status'] == 'OK':
travel_data.append({
'destination': destinations_addr[i],
'distance': element['distance']['text'],
'duration': element['duration']['text']
})
return travel_data
else:
return []
# Example usage
api_key = 'YOUR_API_KEY'
origin = 'Delhi, India'
destinations = ['Mumbai, India', 'Kolkata, India', 'Chennai, India']
results = get_multiple_distances(origin, destinations, api_key)
print(f"Distances from {origin}:")
for result in results:
print(f"To {result['destination']}: {result['distance']}, {result['duration']}")
Key Points
- Always check the
statusfield in the API response for error handling - The API returns both text format (human-readable) and value format (for calculations)
- You can specify units as 'metric' or 'imperial'
- Multiple origins and destinations can be separated by pipe (|) character
- API usage is subject to quotas and billing based on your Google Cloud plan
Conclusion
The Google Distance Matrix API provides an easy way to calculate travel distance and duration between locations programmatically. Always handle API errors gracefully and be mindful of your API quotas when making multiple requests.
