Google Maps API Web Services

The Google Distance Matrix API

  1. Introduction
  2. Audience
  3. API Key
  4. Limits
  5. Distance Matrix Requests
    1. Request Parameters
  6. Distance Matrix Responses
    1. JSON Output
    2. XML Output
    3. Distance Matrix Response Elements

Looking to use this service in a JavaScript application? Check out the DistanceMatrixService class of the Google Maps API v3.

Introduction

The Google Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations. The information returned is based on the recommended route between start and end points, as calculated by the Google Maps API, and consists of rows containing duration and distance values for each pair.

This service does not return detailed route information. Route information can be obtained by passing the desired single origin and destination to the Directions API.

Audience

This document is intended for developers who wish to compute travel distance and time between a number of points using the Google Maps API. The document provides an introduction to using the API, and reference material on the available parameters.

API Key

Note: Maps for Business users must include client and signature parameters with their requests instead of a key.

All Distance Matrix API applications should use an API key. Including a key in your request:

  • Allows you to monitor your application's API usage in the APIs Console.
  • Enables per-key instead of per-IP-address quota limits.
  • Ensures that Google can contact you about your application if necessary.

The Distance Matrix API uses an API key to identify your application. API keys are managed through the Google APIs console. To create your key:

  1. Visit the APIs console at https://code.google.com/apis/console and log in with your Google Account.
  2. Click the Services link from the left-hand menu in the APIs Console, then activate the Distance Matrix API service.
  3. Once the service has been activated, your API key is available from the API Access page, in the Simple API Access section. Distance Matrix API applications use the Key for server apps.

To specify a key in your request, include it as the value of a key parameter.

Note: By default, a key can be used from any server. We strongly recommend that you restrict the use of your key by IP address to servers that you administer. You can specify which IP addresses are allowed to use your API key by clicking the Edit allowed referers... link in the API console.

Note: HTTPS is enforced for requests that include an API key.

Usage Limits

Each query sent to the Distance Matrix API is limited by the number of allowed elements, where the number of origins times the number of destinations defines the number of elements.

The Distance Matrix API has the following limits in place:

Users of the free API:
  • 100 elements per query.
  • 100 elements per 10 seconds.
  • 2 500 elements per 24 hour period.
Maps for Business customers:
  • 625 elements per query.
  • 1 000 elements per 10 seconds.
  • 100 000 elements per 24 hour period.

Maps API for Business customers can purchase additional quota by contacting their Google Enterprise Sales Account Manager.

Distance Matrix API URLs are restricted to approximately 2000 characters, after URL Encoding. As some Distance Matrix API service URLs may involve many locations, be aware of this limit when constructing your URLs. Note that different browsers, proxies, and servers may have different URL character limits as well.

Use of the Distance Matrix API 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

A Distance Matrix API request takes the following form:

http://maps.googleapis.com/maps/api/distancematrix/output?parameters

HTTPS is recommended for applications that include sensitive user data, such as a user's location, in requests:

https://maps.googleapis.com/maps/api/distancematrix/output?parameters

In both cases, output may be either:

  • json (recommended), indicating output in JavaScript Object Notation (JSON); or
  • xml, indicating output as XML.

Request Parameters

Certain parameters are required while others are optional. As is standard in URLs, all parameters are separated using the ampersand (&) character.

Required parameters

  • origins — One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. If you pass coordinates, ensure that no space exists between the latitude and longitude values.
    origins=Bobcaygeon+ON|41.43206,-81.38992
  • destinations — One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, to which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. If you pass coordinates, ensure that no space exists between the latitude and longitude values.
    destinations=Darling+Harbour+NSW+Australia|24+Sussex+Drive+Ottawa+ON|Capitola+CA
  • sensor — Indicates whether your application is using a sensor (such as a GPS locator) to determine the user's location. This value must be either true or false.

Maps API for Business users must include valid client and signature parameters with their Distance Matrix requests. Please refer to the Maps API for Business Web Services chapter for more information.

Optional parameters

  • key — Your application's API key. This key identifies your application for purposes of quota management. Learn how to get a key from the APIs Console.
  • mode — specifies the mode of transport to use when calculating directions. Valid values are:
    • driving (default) indicates standard driving directions using the road network.
    • walking requests walking directions via pedestrian paths & sidewalks (where available).
    • bicycling requests bicycling directions via bicycle paths & preferred streets (currently only available in the US and some Canadian cities).
  • language — The language in which to return results. See the list of supported domain languages. Note that we often update supported languages so this list may not be exhaustive.
  • avoid — Introduces restrictions to the route. Valid values are specified in the Restrictions section of this document. Only one restriction can be specified.
  • units — Specifies the unit system to use when expressing distance as text. See the Unit Systems section of this document for more information.
  • departure_time specifies the desired time of departure as seconds since midnight, January 1, 1970 UTC. The departure time may be specified by Maps for Business customers for to specify the departure_time to receive trip duration considering current traffic conditions. The departure_time must be set to within a few minutes of the current time.

* Note: requests that include the departure_time parameter are limited to 100 elements.

Restrictions

Directions may be calculated that adhere to certain restrictions. Restrictions are indicated by use of the avoid parameter, and an argument to that parameter indicating the restriction to avoid. The following estrictions are supported:

  • avoid=tolls
  • avoid=highways
  • avoid=ferries

* Note: the addition of restrictions does not preclude routes that include the restricted feature; it simply biases the result to more favorable routes.

Unit Systems

Distance Matrix results contain text within distance fields to indicate the distance of the calculated route. The unit system to use can be specified:

  • units=metric (default) returns distances in kilometers and meters.
  • units=imperial returns distances in miles and feet.

* Note: this unit system setting only affects the text displayed within distance fields. The distance fields also contain values which are always expressed in meters.

Distance Matrix Responses

Responses to Distance Matrix API queries are returned in the format indicated by the output flag within the URL request's path.

JSON Output

A sample HTTP request is shown below, requesting distance and duration from Vancouver, BC, Canada and from Seattle, WA, USA, to San Francisco, CA, USA and to Victoria, BC, Canada.

http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false&key=API_KEY

This request will return four elements - two origins times two destinations:

Vancouver to San Francisco Vancouver to Victoria
Seattle to San Francisco Seattle to Victoria

Results are returned in rows, each row containing one origin paired with each destination.

Try it! Click here to send the sample request in your browser. (If prompted to choose an application with which to open the file, you can select your browser or your favorite text editor.)

The JSON result is shown below.

{
  "status": "OK",
  "origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
  "destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
  "rows": [ {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 340110,
        "text": "3 jours 22 heures"
      },
      "distance": {
        "value": 1734542,
        "text": "1 735 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 24487,
        "text": "6 heures 48 minutes"
      },
      "distance": {
        "value": 129324,
        "text": "129 km"
      }
    } ]
  }, {
    "elements": [ {
      "status": "OK",
      "duration": {
        "value": 288834,
        "text": "3 jours 8 heures"
      },
      "distance": {
        "value": 1489604,
        "text": "1 490 km"
      }
    }, {
      "status": "OK",
      "duration": {
        "value": 14388,
        "text": "4 heures 0 minutes"
      },
      "distance": {
        "value": 135822,
        "text": "136 km"
      }
    } ]
  } ]
}

Note that these results generally need to be parsed if you wish to extract values from the results. Parsing JSON is relatively easy. See Parsing JSON for some recommended design patterns.

XML Output

In this example, the Distance Matrix API requests an xml response for the otherwise identical query as above:

http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Vancouver+BC&mode=bicycling&language=fr-FR&sensor=false&key=API_KEY

The XML returned by this request is shown below.

<?xml version="1.0" encoding="UTF-8"?> 
<DistanceMatrixResponse> 
 <status>OK</status> 
 <origin_address>Vancouver, BC, Canada</origin_address> 
 <origin_address>Seattle, État de Washington, États-Unis</origin_address> 
 <destination_address>San Francisco, Californie, États-Unis</destination_address> 
 <destination_address>Victoria, BC, Canada</destination_address> 
 <row> 
  <element> 
   <status>OK</status> 
   <duration> 
    <value>340110</value> 
    <text>3 jours 22 heures</text> 
   </duration> 
   <distance> 
    <value>1734542</value> 
    <text>1 735 km</text> 
   </distance> 
  </element> 
  <element> 
   <status>OK</status> 
   <duration> 
    <value>24487</value> 
    <text>6 heures 48 minutes</text> 
   </duration> 
   <distance> 
    <value>129324</value> 
    <text>129 km</text> 
   </distance> 
  </element> 
 </row> 
 <row> 
  <element> 
   <status>OK</status> 
   <duration> 
    <value>288834</value> 
    <text>3 jours 8 heures</text> 
   </duration> 
   <distance> 
    <value>1489604</value> 
    <text>1 490 km</text> 
   </distance> 
  </element> 
  <element> 
   <status>OK</status> 
   <duration> 
    <value>14388</value> 
    <text>4 heures 0 minutes</text> 
   </duration> 
   <distance> 
    <value>135822</value> 
    <text>136 km</text> 
   </distance> 
  </element> 
 </row> 
</DistanceMatrixResponse> 

We recommend that you use json as the preferred output flag unless your service requires xml for some reason. Processing XML trees requires some care, so that you reference proper nodes and elements. See Parsing XML with XPath for some recommended design patterns for output processing.

The remainder of this documentation will use JSON syntax.

Distance Matrix Response Elements

Distance Matrix responses contain the following root elements:

  • status contains metadata on the request. See Status Codes below.
  • origin_addresses contains an array of addresses as returned by the API from your original request. These are formatted by the geocoder and localized according to the language parameter passed with the request.
  • destination_addresses contains an array of addresses as returned by the API from your original request. As with origin_addresses, these are localized if appropriate.
  • rows contains an array of elements, which in turn each contain a status, duration, and distance element.

Status Codes

The status fields within the response object contain the status of the request, and may contain useful debugging information. The Directions Matrix API returns a top-level status field, with information about the request in general, as well as a status field for each element field, with information about that particular origin-destination pairing.

Top-level Status Codes
  • OK indicates the response contains a valid result.
  • INVALID_REQUEST indicates that the provided request was invalid.
  • MAX_ELEMENTS_EXCEEDED indicates that the product of origins and destinations exceeds the per-query limit.
  • OVER_QUERY_LIMIT indicates the service has received too many requests from your application within the allowed time period.
  • REQUEST_DENIED indicates that the service denied use of the Distance Matrix service by your application.
  • UNKNOWN_ERROR indicates a Distance Matrix request could not be processed due to a server error. The request may succeed if you try again.
Element-level Status Codes
  • OK indicates the response contains a valid result.
  • NOT_FOUND indicates that the origin and/or destination of this pairing could not be geocoded.
  • ZERO_RESULTS indicates no route could be found between the origin and destination.

Error Messages

When the top-level status code is other than OK, there may be an additional error_message field within the Distance Matrix response object. This field contains more detailed information about the reasons behind the given status code.

Note: This field is not guaranteed to be always present, and its content is subject to change.

Rows

When the Distance Matrix API returns results, it places them within a JSON rows array. Even if no results are returned (such as when the origins and/or destinations don't exist), it still returns an empty array. XML responses consist of zero or more <row> elements.

Rows are ordered according to the values in the origin parameter of the request. Each row corresponds to an origin, and each element within that row corresponds to a pairing of the origin with a destination value.

Each row array contains one or more element entries, which in turn contain the information about a single origin-destination pairing.

Elements

The information about each origin-destination pairing is returned in an element entry. An element contains the following fields:

  • status: See Status Codes for a list of possible status codes.
  • duration: The duration of this route, expressed in seconds (the value field) and as text. The textual representation is localized according to the query's language parameter.
  • distance: The total distance of this route, expressed in meters (value) and as text. The textual value uses the unit system specified with the unit parameter of the original request, or the origin's region.

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.