Guidelines for Developers | DistanceMatrixAPI

The DistanceMatrixAPI: Google Maps Alternative

– Before you begin

– Usage Limits

– Request Parameters

– Required Parameters

– Optional Parameters

– Travel Modes

– Traffic Information

– Restrictions

– Unit Systems

– Response example

– Distance Matrix Response Elements

– Status Codes

– Top-level Status Codes

– Element-level Status Codes

– Error Messages

– Rows

– Elements

Distance Matrix API Introduction

This page will guide you through the various requests and response types of the Distance Matrix API and how you can check out data analogous to the Google Distance Matrix API service from DistanceMatrixAPI.

Before you begin

This document is intended for developers who wish to get the distance of the fastest route and travel time  between multiple points. It provides a detailed guideline to using the API and reference material on the available parameters.

The Distance Matrix API is a web HTTP/HTTPS API service that returns that fastest route distance and travel time for a single or multiple locations matrix. Calculations are made for all possible combinations between the starting points to the destination points.

The API yields information that are based on the suggested/fastest route between the start and end points, as calculated by the Distance Matrix API, and they are composed of rows containing travel durations and distances in either kilometers or mile values for each pair of points. Time durations are on the basis of predictive traffic information using real time or historical values, depending on the set departure time as specified in the http/https request.

The Distance Matrix API response returns a distance matrix in JSON or XML format, in addition to data about the travel duration of each consecutive route segment in the matrix. The returned estimated travel duration for a route segment is always accounting for the latest traffic conditions and in case of future request, the traffic forecast. The Distance Matrix API works in every country around the globe, worldwide and is available for all travel modes including driving, transiting, bicycling, walking, and other travel modes.

The API can be used to find the origin and destination points that are the closest to the point of origin or for any other use case. The Distance Matrix API always returns an estimated travel duration and a distance of the fastest route for each element in the matrix, where an element is an origin multiplied by destination pair in the matrix .

For instance, lets assume that there are 3 starting points 1, 2, and 3, and three destination locations X, Y, and Z. DistanceMatrixAPI will calculate the matrix of all travel time in seconds and distances in meters miles between the locations:

0XYZ
11 to X1 to Y1 to Z
22 to X2 to Y2 to Z
33 to X3 to Y3 to Z

The Matrix API calculates travel duration in seconds and shortest distances in Metric or Imperial Units. It however, does not return route geometries.

The travel duration and distance between the points on the map are not always symmetric, since those routes may be different by directions because of to one-way streets or turn blocks. For instance, 1 to X may have a different travel duration estimate than X to 1

Distance Matrix Requests

Request Parameters

The Distance Matrix API request was created specifically to be similar to the Google Distance Matrix API request format. You can get more information from the Simple Migration page.

A Distance Matrix API request takes the following form:

GET

https://maps.distancematrixapi.com/maps/api/distancematrix/json
?origins=<origin_location_1|origin_location_2|...|origin_location_n>
&destinations=<destination_location_1|destination_location_2|...|destination_location_n>
&key=<your_access_token> 

A Distance Matrix API request example:

GET

https://maps.distancematrixapi.com/maps/api/distancematrix/json?origins=51.4822656,-0.1933769&destinations=51.4994794,-0.1269979&key=<your_access_token> 

Required Parameters

  • origins — an individual starting point or multiple points for calculating travel distance and duration. You can input one or more locations separated by the pipe character (|) or the encoded pipe character %7C in the form of an address or latitude/longitude coordinates:
    • If you input an address, the distance matrix api geocodes the parameter and converts it to a latitude/longitude coordinate to calculate the distance and travel time. This coordinate may be different from that returned by the Geocoding API, for example, a building entrance rather than its center. This can cause a shirt of few meters but in most cases it should be fine.
    • If you input a latitude/longitude coordinates, they will be used without changes to return the travel time and shortest distance. Ensure that no space or lines exists between the latitude and longitude parameters.
  • destinations — single or multiple desitation points  to use as the final destinations for calculating travel time estimates and distance. The parameters for the Destination are identical to the Origin parameters, as mentioned above.
  • key — this is the API token or key which you can get by filling the demo form here

Optional Parameters

  • mode (default is driving) : Selects the mode of transport to consider when computing time and distance. Valid parameters and request details are specified in the Travel Modes section of this page.
  • language : Selects the language in that results will be returned.
    • See the list of supported languages. DistanceMatrixAPI often updates the supported languages, so this list may not be the full one. Contact support@distancematrixapi.com to get the full list
    • If your language is not supplied, the API will attempt to use the default language as specified in the Accept-Language header, or the native language of the domain from which the API request is sent from.
    • In case a name is not available in the preferred language, the matrix API will use the nearest one.
  • avoid : Considers restrictions to the route as selected by the API. Possible parameters are mentioned in the Restrictions section of this document. Only one restriction parameter may be specified at a time.
  • units : Selects the distance unit system to use when returning the distance as text. 
  • arrival_time : Sets the desired time of arrival for Distance Matrix requests, in seconds since midnight, January 1, 1970 UTC. You may select either departure_time or arrival_time, but not both. Please note that arrival_time must be set as an integer.
  • departure_time : The desired time of departure. You can select the time as an integer in seconds since midnight, January 1, 1970 UTC. You may also specify a value of now, which sets the departure time to the current time (correct to the nearest second). The departure time can be specified in two use cases:
    • For API requests where the travel mode is set as 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 API requests where the travel mode is driving (the default mode): You may set the departure_time to receive a route and trip duration (response field: duration_in_traffic) that take latest traffic conditions into account. This option is only available if the request contains a valid API key, as provided by DistanceMatrixAPI. The departure_time must be specified to the current or future time. It cannot be a time in the past.
      Note that If departure time is not set, the choice of route and duration are based on live road network and average time-independent traffic conditions. Results for a given API request may be different over time due to changes in the road conditions, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency. This is the magic.
      Note: Distance Matrix requests specifying departure_time when mode=driving are limited to a maximum of 100 elements per request. The number of origins pairs times the number of destinations defines the number of elements.
  • traffic_model (defaults to best_guess) : Specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. The available values for this parameter are:
    • best_guess (default) indicates that the returned duration_in_traffic should be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer the departure_time is to now.
    • pessimistic indicates that the returned duration_in_traffic should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.
    • optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.
  • 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.

As we can see from above. DistanceMatrixAPI Platform is engineered to be very similar to Google Map Distance Matrix API. You can check out there documentation at  https://developers.google.com/maps/documentation/distance-matrix/overview

Travel Modes

For the calculation of distances, you may specify the transportation mode to use. By default, distances are calculated for the driving mode. 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 a DistanceMatrixAPI token. 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.

Traffic Information

Traffic information is used when all the following apply (these are the conditions required to receive the duration_in_traffic field in the Distance Matrix response):

  • The travel mode parameter is driving, or is not specified (driving is the default travel mode).
  • The request includes a valid departure_time parameter. The departure_time can be set to the current time or some time in the future. It cannot be in the past.

Optionally, you can include the traffic_model parameter in your request to specify the assumptions to use when calculating time in traffic.

Restrictions

Distances 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 restrictions are supported:

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

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

Response example

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.

BODY

{
  "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": 340124,
            "text": "3 jours 23 heures"
          },
          "distance": {
            "value": 1734552,
            "text": "1 745 km"
          }
        },
        {
          "status": "OK",
          "duration": {
            "value": 24489,
            "text": "6 heures 49 minutes"
          },
          "distance": {
            "value": 129330,
            "text": "130 km"
          }
        }
      ]
    },
    {
      "elements": [
        {
          "status": "OK",
          "duration": {
            "value": 288850,
            "text": "3 jours 9 heures"
          },
          "distance": {
            "value": 1489654,
            "text": "1 492 km"
          }
        },
        {
          "status": "OK",
          "duration": {
            "value": 14385,
            "text": "4 heures 0 minutes"
          },
          "distance": {
            "value": 135811,
            "text": "136 km"
          }
        }
      ]
    }
  ]
} 

DistanceMatrixAPI Response Elements

The Distance Matrix API responses contain the following parameters and 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 Distance 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_DAILY_LIMIT indicates any of the following:
    • The API key is missing or invalid.
    • Billing has not been enabled on your account. Or accounts funds are depleted
    • A self-imposed usage cap has been exceeded.
    • The provided method of payment is no longer valid (for example, a credit card has expired).
  • See the Maps FAQ to learn how to fix this.
  • 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.
  • MAX_ROUTE_LENGTH_EXCEEDED indicates the requested route is too long and cannot be processed.

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.

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.
  • duration_in_traffic: The length of time it takes to travel this route, based on current and historical traffic conditions. See the traffic_model request parameter for the options you can use to request that the returned value is optimistic, pessimistic, or a best-guess estimate. The duration is 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.

Easy To Integrate Distance Matrix API

Are you a developer working for a company or an ongoing project which uses or plans to use Distance Matrix API ?