Data Analyse Breda

Django Google Maps Tutorial #3: Calculate Distance and Duration with Distance Matrix API

In this tutorial series I show how you can use the Google Maps API in your Django application. This API can be used for geocoding, reverse geocoding, distance calculations, and displaying maps in your application.

In this post we will use the Google Maps Distance Matrix API to calculate the distance between two locations. In previous posts we focused on setting up the API in Google Cloud Platform, and Geocoding an adress string.

Before you can use the Google Maps API you need the following things:

  • Enable the Google Maps API on the Google Cloud Platform.
  • Specify the credentials of the API in the settings.py file of your Django app.

Both of these steps have been covered in the previous blogpost.

What are we going to do?

In this post I will explain:

  • What can you do with the distance matrix API
  • How to create a basic distance matrix request in your view
  • How can you display the distance and duration values

In this tutorial I use the adress string to calculate the distance between 2 locations. Differences are minimal, but Google recommends using the place_id. In Googles words: “Using coordinates will always result in the point being snapped to the road nearest to those coordinates – which may not be an access point to the property, or even a road that will quickly or safely lead to the destination. Using the address will provide the distance to the center of the building, as opposed to an entrance to the building.”

What can you do with the distance API?

The Google Maps Distance Matrix API provides the user with the ability to extract the distance and duration between two location points.

In this tutorial we will use the Google Maps Python Client to make a request with a start adress, destination adress, mode of transport, and departure time and extract the distance and duration of the journey.

How to create a basic distance matrix request in your view

I have created a view called distance where we use the Google Maps Python Client to calculate the distance between 2 points.

def distance(request):
    gmaps = googlemaps.Client(key= settings.GOOGLE_API_KEY)
    now = datetime.now()
    result = gmaps.distance_matrix("Rat Verlegh Stadion",
                                "Breda Station",
                                mode="driving",
                                departure_time=now)
    context = {
        'result':result,
    }
    return render(request, 'google/distance.html',context)
  • gmaps: Connects to the Google Maps Python clients and authenticates with the API key from our settings.py file.
  • now: Gets the current time.
  • result: Uses the Google Python client and specifies our starting point (“Rat verlegh stadion”), the destination (“Breda Station”), our mode of transport and our departure time.

You can use 4 different modes of transports in your request: driving, walking, bicycling, and transit.

We print the result in our html file, to check what output Google gives us.

{% extends 'google/base.html' %}
{% block content %}

<div class="pageholder">
    <div class="titleholder"> 
        <div class="title"><i class="fas fa-people-arrows mr-2"></i> Google Maps #2: Distance </div>
        <a href="{% url 'home'%}" class="title2 mr-4"><i class="fas fa-home mr-2"></i> Back to home </a>
    </div>

    <div class="linkholder">
        {{result}}
    </div>
   

</div>
{% endblock %}

The output we receive is a string of different kind of datapoints.

The documentation provides us with an example of what the json string looks like when it is structured.

{
  "destination_addresses": ["New York, NY, USA"],
  "origin_addresses": ["Washington, DC, USA"],
  "rows":
    [
      {
        "elements":
          [
            {
              "distance": { "text": "228 mi", "value": 367654 },
              "duration": { "text": "3 hours 55 mins", "value": 14078 },
              "status": "OK",
            },
          ],
      },
    ],
  "status": "OK",
}

How can you display the distance and duration values

Let’s extract the distance and duration of our request. In order to do this, we first need to alter our view. We add json.dumps and json.loads so that we are able to query the results. Json.dumps will convert the python response into a string. Json.loads will take the string and convert it to an object that we can query.

def distance(request):
    gmaps = googlemaps.Client(key= settings.GOOGLE_API_KEY)
    now = datetime.now()
    calculate = json.dumps(gmaps.distance_matrix("Rat Verlegh Stadion",
                            "Breda Station",
                            mode="driving",
                            departure_time=now)) 
    calculate2 = json.loads(calculate)
    
    result = calculate2
    distance = calculate2['rows'][0]['elements'][0]['distance']
    duration = calculate2['rows'][0]['elements'][0]['duration']

    context = {
        'result':result,
        'distance':distance,
        'duration':duration
    }
    return render(request, 'google/distance.html',context)

You can see in the distance and duration variable that you gradually need to drill down to the correct level in order to get the right information. We can now display the distance and duration in our html file.

...
    <div class="linkholder">
        <div> <b>The distance is: </b>{{distance}} </div>
    </div>

    <div class="linkholder">
        <div><b>The duration is:</b> {{duration}}</div>
    </div>
...

The output in our browser will now look like this:

If you want to only extract the value or text you can go one level deeper in your view like this:

...
distance = calculate2['rows'][0]['elements'][0]['distance']['value']
duration = calculate2['rows'][0]['elements'][0]['duration']['text']
...

The value attribute of the distance category is displayed in meters. The duration value is displayed in seconds.

That’s all for today!

In this tutorial you learned how to use the Distance Matrix API, one of Googles powerfull APIs that can be used with their Python client. In the next tutorial we will focus on displaying a route on a map in our application.

Leave a Reply