Get Distance and Duration Between Two Places using Google Map and Python

Kingsley Ihemere
3 min readJan 4, 2023

Introduction

To get the distance and duration between two places using Google map and python has become essential task applications that deal with location data.

Google Maps is a popular service that allows users to search for places, get directions, and see real-time traffic updates.

Businesses That Need Google Map Distance Calculation

The Transport companies
Logistic Companies
Hospitality Businesses
Delivery Businesses

These companies depends heavily on data, hence they take advantage of cloud storage systems provided by cloud providers like GCP, Azure, AWS and others.

I have an article on how to load data efficiently into Google’s Cloud Storage with python

In this tutorial, we will learn how to use the Google Maps API to calculate the distance between two points in Python.

To get started, you will need to sign up for a Google Maps API key.

You can do this by visiting the Google Cloud Console and creating a new project. Once you have created your project, you will need to enable the Google Maps Distance Matrix API.

This API allows you to calculate the distance between two points using various modes of transportation, such as driving, walking, and biking.

Once you have enabled the Distance Matrix API, you can use the following Python code to calculate the distance between two points:

Code Explanation

This code uses the distance_matrix method of the googlemaps client to calculate the distance between the two points.

The distance_matrix method returns a JSON object containing the distance and other information about the route.

We can extract the distance and duration from the JSON object by using the following code:

The distance variable now contains the distance between the two points as a string.

You can also specify the mode of transportation when calculating the distance. For example, you can use the following code to calculate the distance by walking:

You can also specify other options when calculating the distance, such as the departure or arrival time.

For more information about the Google Maps Distance Matrix API, you can check out the documentation on the Google Cloud website.

Conclusion

In this tutorial, we learned how to get distance and duration between two places using google map and python.

With this knowledge, you can build location-based applications that can provide users with useful information about distances and directions.

Originally published at https://dekings.dev on January 4, 2023.

--

--

Kingsley Ihemere

A Data Analyst/Data Engineer, I build and analyze with Python(Django & FastAPI), JavaScripts(Vue.js), SQL, Excel, Google Cloud Platform, Power BI & Tableau.