Google Distance Matrix API Guide
Start Here: Official Google Resources
Always consult Google's official documentation first. If you don't understand something, use AI tools like Cursor or Microsoft Copilot to help explain it to you and adjust it to your needs. These tools are incredibly helpful for understanding & fixing code.
What is an API and Why is it Useful?
An API (Application Programming Interface) is like a bridge that lets your code 'talk to' a database somewhere else. In this case, we are 'talking to' Google's massive database of maps and location data. Documentation on how to use the API is exhaustively detailed in the official documentation above (and we have a small example below to get you started). Instead of guessing travel times or distances between places, you can tap directly into Google's knowledge of roads, traffic patterns, and travel routes worldwide.
Why this is exciting for your projects: You can find distances or travel times between any two points on the planet by getting data directly from Google's huge database, which can help you make informed answers to your exciting research questions. The best thing is, you can adjust the code to request different data from Google that can be used to help guide your research.
What the API Does
- Computes distance and estimated travel time between origins and destinations
- Supports multiple origins and destinations in one request (e.g. 5 origins × 5 destinations = 25 results)
- Offers multiple travel modes: driving, walking, bicycling, and transit
- Can factor in traffic during different times if requested
What You'll Need
- A Google Cloud account: cloud.google.com
- An active billing account (Google provides $200 worth of free credit, which is more than enough for normal use)
- An API key with the Distance Matrix API enabled
Input: What You Provide
You make a request by calling a URL like this:
https://maps.googleapis.com/maps/api/distancematrix/json
?origins=Belfast
&destinations=Dublin
&mode=driving
&departure_time=now
&key=YOUR_API_KEY
Parameters
origins: one or more addresses or latitude/longitude pairs (separated by | if more than one)
destinations: same as above, can also be multiple
mode: travel mode (driving, walking, bicycling, transit)
departure_time: optional but useful for traffic-based estimates (set to "now" for current traffic)
key: your API key
Output: What You Get Back
The API returns a JSON object structured like this:
{
"destination_addresses": ["Dublin, Ireland"],
"origin_addresses": ["Belfast, UK"],
"rows": [
{
"elements": [
{
"distance": {
"text": "167 km",
"value": 167000
},
"duration": {
"text": "1 hour 45 mins",
"value": 6300
},
"status": "OK"
}
]
}
]
}
Key Fields
origin_addresses and destination_addresses: resolved, human-readable names of your inputs
rows[n].elements[m]: contains the data from origin n to destination m
distance.text / value: human-readable vs. meters
duration.text / value: human-readable vs. seconds
status: returns "OK" if successful, or an error message otherwise
Working Python Example
Here's a practical example that accepts user input and displays results, that works exactly like what we detailed above. It requests information from the URL (with paramters you specify, like shown above), and returns a JSON object with the results. You can just copy paste this code into Replit/ Visual Studio/ Cursor/ Jupyter Notebook/ etc. and run it!:
import requests
def get_distance_matrix(origin, destination, api_key):
url = "https://maps.googleapis.com/maps/api/distancematrix/json"
params = {
'origins': origin,
'destinations': destination,
'mode': 'driving',
'departure_time': 'now',
'key': api_key
}
response = requests.get(url, params=params)
data = response.json()
if data['status'] == 'OK':
element = data['rows'][0]['elements'][0]
if element['status'] == 'OK':
distance = element['distance']['text']
duration = element['duration']['text']
print(f"Distance: {distance}, Time: {duration}")
else:
print("Route not found")
else:
print(f"API Error: {data['status']}")
# Example usage
api_key = "YOUR_API_KEY_HERE"
origin = "Belfast, UK"
destination = "Dublin, Ireland"
get_distance_matrix(origin, destination, api_key)
Additional Resources
For a more comprehensive example with datasets, see this GitHub repository from a previous semester:
Geospatial Data Analytics Project - Contains practical implementation examples and datasets
Need Help?
Any questions, email your module coordinator or use an AI tool like those mentioned below to help understand the code and get your desired output.
Recommended AI Tools
If you don't understand something in Google's documentation, these AI tools can help explain concepts and generate code: