The idea of this article is to simply demonstrate something that can have many uses and be an extremely valuable tool: the Google Maps Distance API (https://developers.google.com/maps/documentation/distance-matrix).
I received a request to calculate the driving distance between two points. That’s straightforward, but we were talking about 25,000 address pairs recorded in an Excel spreadsheet. The structure of the spreadsheet was like this:
Delivery Address | Store Address |
---|---|
Target address | Source address |
Target address | Source address |
Target address | Source address |
The expected output needed to include a third column containing the distance between the addresses in column B and column A, like this:
Delivery Address | Store Address | Distance |
---|---|---|
Target Address | Source Address | 2.3 mi |
Target Address | Source Address | 1.6 mi |
Target Address | Source Address | 1.7 mi |
To complete this task, I considered the following set of tools:
- Google Maps Distance API, which at the time of writing this article, includes a monthly free tier, allowing approximately 2,750 free requests per month.
- Python
- Python module Google Maps (googlemaps). The list of modules (and versions) used for the task are:
certifi==2024.6.2
charset-normalizer==3.3.2
et-xmlfile==1.1.0
googlemaps==4.10.0
idna==3.7
numpy==1.26.4
openpyxl==3.1.3
pandas==2.2.2
python-dateutil==2.9.0.post0
pytz==2024.1
requests==2.32.3
six==1.16.0
tzdata==2024.1
urllib3==2.2.1
The code will read the file with the source addresses, load the addresses into a Pandas dataframe, and through API requests, it will calculate the distance between each pair of addresses and add the result in a new column in the dataframe. In the end, it will generate a new xlsx file with the results. The code and its details can be found on my Github: https://github.com/rccardoso/googlemapsapi