Create a distance matrix in Python with the Google Maps API
Use the google maps API to obtain distances and duration between locations
What you will learn in this article
How to calculate the actual duration and distance according to google maps
How to export your results in a clean excel
How to iterate over each possible combination
Step 0: Environment preparation
Install the googlemaps package & import pandas & itertools.
Step 1: Load the data
For learning purposes, I have created a dummy dataset. You can download the dataset here.
You can also directly load the dataset if you are using google collab. More info in this article.
Read in the dataset with the longitude & latitude coordinates (X-coordinate = Latitude, Y-coordinate = Longitude).
Step 2: Connect to the Google API services
Connect to your local Google account by using your personal API key.
Make sure that you have enabled the distance matrix API.
Step 3: Initialize export lists
We are going to write out our API calls results to separate lists for each variable:
Origin ID: This is the ID of the origin location. We can link this back to our locations.
Destination ID: This is the ID of the destination location. We can link this back to our location.
Distance: We will store the estimated distance here.
Time: We will store the estimated duration here.
Step 4: Loop over the locations
This function enables us to take a location and loop over all the possible destination locations, fetching the estimated duration and distance
Step 5: Consolidate the lists in a dataframe
In this step, we will consolidate the lists in one dataframe.
Step 6: Merge the consolidated dataframe with the input file
Merge the results file with the original excel file to gain the names & coordinates of the original locations.
Happy programming!
Cheers,
Ewoud