Click here to see your recently viewed pages and most viewed pages.
Hide
Google Maps Distance Matrix API

The Google Distance Matrix API

This service is also available as part of the Google Maps JavaScript API, or with a Java client library.

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

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

To get started using Distance Matrix API, you need to create or select a project in the Google Developers Console and enable the API. Click this link, which guides you through the process and activates the Distance Matrix API automatically.

Alternatively, you can activate the Distance Matrix API yourself in the Developers Console by doing the following:

  1. Go to Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, expand APIs & auth. Next, click APIs. Select the Enabled APIs link in the API section to see a list of all your enabled APIs. Make sure that the Distance Matrix API is on the list of enabled APIs. If you have not enabled it, select the API from the list of APIs, then select the Enable API button for the API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the Credentials page where you can access your project's credentials.

If your project doesn't already have a Server Key, create an API key by selecting Create New Key and then selecting Server Key. Do not use this key outside of your server code. For example, do not embed it in a web page or in a mobile application. To prevent quota theft, restrict your key so that requests are only allowed from your servers' source IP addresses.

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 Google Developers Console.
  • Enables per-key instead of per-IP-address quota limits.
  • Ensures that Google can contact you about your application if necessary.

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

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.
  • 2500 elements per 24 hour period.
Google Maps API for Work customers:
  • 625 elements per query.
  • 1000 elements per 10 seconds.
  • 100 000 elements per 24 hour period.

Google Maps API for Work 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:

https://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.

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

Google Maps API for Work users must include valid client and signature parameters with their Distance Matrix requests. Please refer to the Google Maps API for Work 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 Google Developers Console.
  • mode (defaults to driving) — Specifies the mode of transport to use when calculating distance. Valid values and other request details are specified in the Travel Modes section of this document.
  • 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 — The desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC. Alternatively, you can specify a value of now, which sets the departure time to the current time (correct to the nearest second). The departure time may be specified in two cases:
    • For requests where the travel mode is transit: You can optionally specify one of departure_time or arrival_time. If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time).
    • For requests where the travel mode is driving: Google Maps API for Work customers can 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.
  • arrival_time — Specifies the desired time of arrival for transit requests, in seconds since midnight, January 1, 1970 UTC. You can specify either departure_time or arrival_time, but not both. Note that arrival_time must be specified as an integer.
  • transit_mode — Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. The parameter supports the following arguments:
    • bus indicates that the calculated route should prefer travel by bus.
    • subway indicates that the calculated route should prefer travel by subway.
    • train indicates that the calculated route should prefer travel by train.
    • tram indicates that the calculated route should prefer travel by tram and light rail.
    • rail indicates that the calculated route should prefer travel by train, tram, light rail, and subway. This is equivalent to transit_mode=train|tram|subway.
  • transit_routing_preference — Specifies preferences for transit requests. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. This parameter may only be specified for requests where the mode is transit. The parameter supports the following arguments:
    • less_walking indicates that the calculated route should prefer limited amounts of walking.
    • fewer_transfers indicates that the calculated route should prefer a limited number of transfers.

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

Travel Modes

For the calculation of distances, you may specify the transportation mode to use. By default, distances are calculated for driving directions. The following travel modes are supported:

  • driving (default) indicates distance calculation using the road network.
  • walking requests distance calculation for walking via pedestrian paths & sidewalks (where available).
  • bicycling requests distance calculation for bicycling via bicycle paths & preferred streets (where available).
  • transit requests distance calculation via public transit routes (where available). This value may only be specified if the request includes an API key or a Google Maps API for Work client ID. If you set the mode to transit you can optionally specify either a departure_time or an arrival_time. If neither time is specified, the departure_time defaults to now (that is, the departure time defaults to the current time). You can also optionally include a transit_mode and/or a transit_routing_preference.

Note: Both walking and bicycling directions may sometimes not include clear pedestrian or bicycling paths, so these directions will return warnings in the returned result which you must display to the user.

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.

Two sample HTTP requests are 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.

This request demonstrates using the JSON output flag:

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

This request demonstrates using the XML output flag:

https://maps.googleapis.com/maps/api/distancematrix/xml?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Vancouver+BC&mode=bicycling&language=fr-FR&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.)

Click the tabs below to see the sample JSON and XML responses.

JSON
{
  "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
<?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 length of time it takes to travel 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.
  • fare: If present, contains the total fare (that is, the total ticket costs) on this route. This property is only returned for transit requests and only for transit providers where fare information is available. The information includes:
    • currency: An ISO 4217 currency code indicating the currency that the amount is expressed in.
    • value: The total fare amount, in the currency specified above.

Below is an example of an element containing fare information:

{
  "status": "OK",
  "duration": {
    "value": 340110,
    "text": "3 jours 22 heures"
  },
  "distance": {
    "value": 1734542,
    "text": "1 735 km"
  }
  "fare" : {
    "currency" : "USD",
    "value" : 6
  },
}

The sensor Parameter

The Google Maps API previously required that you include the sensor parameter to indicate whether your application used a sensor to determine the user's location. This parameter is no longer required.