Google Maps JavaScript API v3

Distance Matrix Service

  1. Overview
  2. Usage Limits and Requirements
  3. Distance Matrix Requests
  4. Distance Matrix Responses
    1. Results
    2. Status Codes
    3. Parsing the Results

Overview

Google's Distance Matrix service computes travel distance and journey duration between multiple origins and destinations using a given mode of travel.

This service does not return detailed route information. Route information, including polylines and textual directions, can be obtained by passing the desired single origin and destination to the Directions Service.

Usage limits and requirements

Quotas

The following usage limits are in place for the Distance Matrix service:

  • Maximum of 25 origins or 25 destinations per request; and
  • At most 100 elements (origins times destinations) per request.

Requests are also rate limited. If too many elements are requested within a certain time period, an OVER_QUERY_LIMIT response code will be returned.

Display of a Google Map

Use of the Distance Matrix service must relate to the display of information on a Google Map; for example, to determine origin-destination pairs that fall within a specific driving time from one another, before requesting and displaying those destinations on a map. Use of the service in an application that doesn't display a Google map is prohibited.

Distance Matrix Requests

Accessing the Distance Matrix service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request, to process the results.

You access the Distance Matrix service within your code via the google.maps.DistanceMatrixService object. The DistanceMatrixService.getDistanceMatrix() method initiates a request to the Distance Matrix service, passing it an object literal containing the origins, destinations, and travel mode, as well as a callback method to execute upon receipt of the response.

var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = "Greenwich, England";
var destinationA = "Stockholm, Sweden";
var destinationB = new google.maps.LatLng(50.087692, 14.421150);

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: UnitSystem,
    durationInTraffic: Boolean,
    avoidHighways: false,
    avoidTolls: false
  }, callback);

function callback(response, status) {
  // See Parsing the Results for
  // the basics of a callback function.
}

View example (distance-matrix.html)

The object literal passed to the service contains the following fields:

  • origins (required) — An array containing one or more address strings and/or google.maps.LatLng objects, from which to calculate distance and time.
  • destinations (required) — An array containing one or more address strings and/or google.maps.LatLng objects, to which to calculate distance and time.
  • travelMode (optional) — specifies what mode of transport to use when calculating directions. Valid values are:
    • google.maps.TravelMode.DRIVING (default) indicates standard driving directions using the road network.
    • google.maps.TravelMode.WALKING requests walking directions via pedestrian paths & sidewalks (where available).
    • google.maps.TravelMode.BICYCLING requests bicycling directions via bicycle paths & preferred streets (currently only available in the US and some Canadian cities).
  • unitSystem (optional) — The unit system to use when displaying distance. Accepted values are:
    • google.maps.UnitSystem.METRIC (default)
    • google.maps.UnitSystem.IMPERIAL
  • durationInTraffic (optional) specifies whether the elements should include a duration that takes into account current traffic conditions. This feature is only available for Maps for Business customers. The time in current traffic will only be returned if traffic information is available in the requested area.

  • avoidHighways (optional) — If true, the routes between origins and destinations will be calculated to avoid highways where possible.
  • avoidTolls (optional) — If true, the directions between points will be calculated using non-toll routes, wherever possible.

Distance Matrix Responses

A successful call to the Distance Matrix service returns a DistanceMatrixResponse object and a DistanceMatrixStatus object. These are passed to the callback function you specified in the request.

The DistanceMatrixResponse object contains distance and duration information for each origin/destination pair for which a route could be calculated.

{
  "origin_addresses": [ "Greenwich, Greater London, UK", "13 Great Carleton Square, Edinburgh, City of Edinburgh EH16 4, UK" ],
  "destination_addresses": [ "Stockholm County, Sweden", "Dlouhá 609/2, 110 00 Praha-Staré Město, Česká republika" ],
  "rows": [ {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 70778,
        "text": "19 hours 40 mins"
      },
      "distance": {
        "value": 1887508,
        "text": "1173 mi"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 44476,
        "text": "12 hours 21 mins"
      },
      "distance": {
        "value": 1262780,
        "text": "785 mi"
      }
    } ]
  }, {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 96000,
        "text": "1 day 3 hours"
      },
      "distance": {
        "value": 2566737,
        "text": "1595 mi"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 69698,
        "text": "19 hours 22 mins"
      },
      "distance": {
        "value": 1942009,
        "text": "1207 mi"
      }
    } ]
  } ]
}

Distance Matrix Results

The supported fields in a response are explained below.

  • originAddresses is an array containing the locations passed in the origins field of the Distance Matrix request. The addresses are returned as they are formatted by the geocoder.
  • destinationAddresses is an array containing the locations passed in the destinations field, in the format returned by the geocoder.
  • rows is an array of DistanceMatrixResponseRow objects, with each row corresponding to an origin.
  • elements are children of rows, and correspond to a pairing of the row's origin with each destination. They contain status, distance, and duration information for each origin/destination pair.
  • The distance, duration and duration_in_traffic fields for each element include both a value (which is always shown in meters or seconds), and a text field, which supplies a more human-readable version of the information. The distance's text value is formatted according to the unitSystem specified in the request (or in metric, if no preference was supplied).

Status Codes

The Distance Matrix response includes a status code for the response as a whole, as well as a status for each element.

Response Status Codes

Status codes that apply to the DistanceMatrixResponse are passed in the DistanceMatrixStatus object and include:

  • OK — The request is valid. This status can be returned even if no routes were found between any of the origins and destinations. See Element Status Codes for the element-level status information.
  • INVALID_REQUEST — The provided request was invalid. This is often due to missing required fields. See the list of supported fields above.
  • MAX_ELEMENTS_EXCEEDED — The product of origins and destinations exceeds the per-query limit.
  • MAX_DIMENSIONS_EXCEEDED — Your request contained more than 25 origins, or more than 25 destinations.
  • OVER_QUERY_LIMIT — Your application has requested too many elements within the allowed time period. The request should succeed if you try again after a reasonable amount of time.
  • REQUEST_DENIED — The service denied use of the Distance Matrix service by your web page.
  • UNKNOWN_ERROR — A Distance Matrix request could not be processed due to a server error. The request may succeed if you try again.

Element Status Codes

The following status codes apply to specific DistanceMatrixElement objects:

  • NOT_FOUND — The origin and/or destination of this pairing could not be geocoded.
  • OK — The response contains a valid result.
  • ZERO_RESULTS — No route could be found between the origin and destination.

Parsing the Results

The DistanceMatrixResponse object contains one row for each origin that was passed in the request. Each row contains an element field for each pairing of that origin with the provided destination(s).

function callback(response, status) {
  if (status == google.maps.DistanceMatrixStatus.OK) {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
        var element = results[j];
        var distance = element.distance.text;
        var duration = element.duration.text;
        var from = origins[i];
        var to = destinations[j];
      }
    }
  }
}

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.