Skip to content
Products
Solutions
By industry
By use case
Resources
Products
Solutions
By industry
By use case
Resources
Products
Solutions
By industry
By use case
Resources
How to Use the Distance Matrix API
Yaron Fidler
Product Manager, Google Maps Platform
Feb 11, 2020
Try Google Maps Platform
Unlock access to real-world data and insights with a monthly $200 Google Maps Platform credit.
Get started

When you use Google Maps Platform to plot multiple locations, you can see nearby markers visually. However, their true distance isn’t always clear, especially when factoring in traffic. You can quantify how close two points are by calculating the distance using the Maps Javascript API, but when you want to determine many distances at once, the Distance Matrix API can help you out and get all the data you need in a single call. For example, you can narrow a list of restaurants by delivery time, assign multiple delivery drivers based on proximity, or determine the nearest technician to a customer to dispatch. 

In this post, we’ll show you how to use the Distance Matrix API using a common use case–technician dispatching. First, it’s important to understand all the data that is returned from the API, so we’ll start with a basic example identifying the driving distances between major Midwestern cities.

Add map markers for each city

Before you calculate any distances, it’s useful to see the locations on a map. To do that, you’ll need to create markers for our quintet of cities: Chicago, Milwaukee, Detroit, Indianapolis, and St. Louis.

Here’s some HTML and JavaScript to create a map with these cities marked:

<!DOCTYPE html>
<html>
  <head>
    <style>
       /* Set the size of the div element that contains the map */
      #map {
        height: 400px;  /* The height is 400 pixels */
        width: 600px;  /* The width is 600 pixels */
       }
    </style>
  </head>
  <body>
    <!--The div element for the map -->
    <div id="map"></div>
    <script>
      // Initialize and add the map
      let map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 6,
          center: {lat: 41, lng: -86}
        });

        const cities = [
          {lat: 41.88, lng: -87.62}, // Chicago
          {lat: 43.05, lng: -87.95}, // Milwaukee
          {lat: 42.33, lng: -83.04}, // Detroit
          {lat: 39.76, lng: -86.15}, // Indianapolis
          {lat: 38.62, lng: -90.19} // St. Louis
        ];

        // Loop through cities, adding markers
        for (let i=0; i<cities.length; i++) {
          let position = cities[i]; // location of one city
          // create marker for a city
          let mk = new google.maps.Marker({position: position, map: map});
        }

        // Add Distance Matrix here
      }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>
Copied to clipboard!

Find your API Key in the Google Cloud Console and put it in place of YOUR_API_KEY in the code above. In addition to creating a basic map centered in the midwestern United States, the code above creates five markers—one for each of the cities in our example.

When you save the code and load it in a browser, you’ll see a map like the one above. You can probably tell just by looking which city is closest to Chicago, but let’s see how a distance matrix can quantify the solution.

Visualize the distance matrix with a mileage table

The concept behind the Distance Matrix API comes from a time before smartphones and ubiquitous GPS. Travelers would reference printed materials to determine driving distances and durations. You could find two-dimensional mileage tables with city names along the left side and top. Within those tables, found on a paper map in your car or posted on a wall at a gas station, were the distances between the cities in each row and column.

If you were near Chicago, for example, you could quickly read across the first row to see the distance to Milwaukee (92 miles) or Detroit (281 miles). The diagonal pattern of empty cells is a quick heads up that you’re looking at a mileage table—there’s no driving from Chicago to Chicago, after all.

The Distance Matrix API is a modernized take on this glove box classic. You have complete control over the origins in each row and destinations in each column, which allows you to recreate a classic distance matrix, or use a single origin with multiple destinations. Best of all, there’s no need to print these out. You can make a request and have your answer in JSON in seconds.

Calculate drive times from multiple origins

Distances between cities may be fine for paper road maps, but today’s applications have more granular needs that can be supported by the Distance Matrix API. For example, the API is useful for dispatch and delivery, where you have a number of origins or destinations. Let’s see how you can use the Distance Matrix API to choose the closest repair technician.

This usage of the Distance Matrix API includes one destination (the customer) and multiple origins (each potential technician). We’ll assume you know the current position of each technician, such as from GPS.

Add the following code to your map JavaScript after the // Add Distance Matrix here comment:

const service = new google.maps.DistanceMatrixService(); // instantiate Distance Matrix service
      const matrixOptions = {
        origins: ["41.8848274,-87.6320859", "41.878729,-87.6301087", "41.8855277,-87.6440611"], // technician locations
        destinations: ["233 S Wacker Dr, Chicago, IL 60606"], // customer address
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.IMPERIAL
      };
      // Call Distance Matrix service
      service.getDistanceMatrix(matrixOptions, callback);

      // Callback function used to process Distance Matrix response
      function callback(response, status) {
        if (status !== "OK") {
          alert("Error with distance matrix");
          return;
        }
        console.log(response);        
      }
Copied to clipboard!

Since there is a single destination and multiple origins, the results will include multiple rows, each with a single result. In visual distance matrix terms, you’ll be parsing a single column. When the results are returned to the callback function, the code simply logs the response to the browser console. You can inspect it with your browser’s developer tools, or review the JSON payload:

{
  "originAddresses": [ "120 W Randolph St, Chicago, IL 60602, USA", "204 S Clark St, Chicago, IL 60604, USA", "629 N Desplaines St, Chicago, IL 60661, USA" ],
  "destinationAddresses": [ "233 S Wacker Dr, Chicago, IL 60606, USA"],
"rows": [ {
  "elements": [ {
    "status": "OK",
    "duration": {
      "Value": 458,
      "text": "8 mins"
    },
    "distance": {
      "value": 1911,
      "text": "1.2 mi"
    }
  }], {
  "elements": [ {
    "status": "OK",
    "duration": {
      "value": 220,
      "text": "4 mins"
    },
    "distance": {
      "value": 924,
      "text": "0.6 mi"
    }
  }], {
  "elements": [ {
    "status": "OK",
    "duration": {
      "value": 383,
      "text": "6 mins"
    },
    "distance": {
      "value": 1531,
      "text": "1.0 mi"
    }
  }]
}]
}
Copied to clipboard!

The origin and destination addresses are returned at the top level of the response. They can help you make sense of which distance is which. The origins, which were input as latitude/longitude coordinates, have automatically been reverse geocoded to the nearest address.

The rows array has three items, one for each origin (the technicians). Within each row, there is an elements array that includes a result for each destination. Individual results include a status, duration, and distance.

Now that you understand the Distance Matrix data, you’ll want to use it. For example, you could populate a table, share distances on the map, or search through for the shortest drive.

Find the nearest location by drive time

We want to dispatch the nearest technician to the customer location. To do that, we’ll parse the distance matrix JSON to find the shortest drive time.

Add this code after the console.log of the Distance Matrix callback:

let routes = response.rows[0].elements;
          const leastseconds = 86400; // 24 hours
          let drivetime = "";
          let closest = "";

          for (let i=0; i<routes.length; i++) {
            const routeseconds = routes[i].elements[0].duration.value;
            if (routeseconds > 0 && routeseconds < leastseconds) {
              leastseconds = routeseconds; // this route is the shortest (so far)
              drivetime = routes[i].elements[0].duration.text; // hours and minutes
              closest = response.originAddresses[i]; // city name from destinations
            }
          }
          alert("The closest location is " + closest + " (" + drivetime + ")");
Copied to clipboard!

This code loops through all the rows, looking in the first (and only) element of each to find the driving duration. Next, it compares drive time to the current lowest time. By the end, you’ll have discovered the closest location.

You have now parsed the results to find the closest technician—in this case it’s the one at 204 S Clark St, who is only four minutes away. Here, it’s communicated with a JavaScript alert, but in reality you would assign the technician to the customer, likely with a call to your own backend system.

This post gave a few examples of using the Distance Matrix API but there’s much more to explore. You can build off these examples to make your own dispatch service, delivery route planner, or even old school mileage table. Once you have a route selected, you can use the Directions Service to plot it on the map, completing the visual for your users. 

For more information on Google Maps Platform, visit our website.

Clay cityscape
Clay cityscape
Google Maps Platform
Get going with Google Maps Platform