Python and Google Maps Distance API

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 AddressStore Address
Target addressSource address
Target addressSource address
Target addressSource address
Excel file containing addresses pairs

The expected output needed to include a third column containing the distance between the addresses in column B and column A, like this:

Delivery AddressStore AddressDistance
Target AddressSource Address2.3 mi
Target AddressSource Address1.6 mi
Target AddressSource Address1.7 mi
Excel file containing addresses pairs and the result of distance calculation

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

About the Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may also like these