Navigation | Distance Matrix API | Overview | 2GIS Documentation

Distance Matrix API

Distance Matrix API allows you to get information about travel time and distance between points on the map.

You can specify multiple starting points and the same number of ending points and get distance and travel time between each possible pair of starting and ending points. For example, for three starting points (A, B, C) and three ending points (D, E, F), Distance Matrix API calculates distance and travel time of nine route options: AD, AE, AF, BD, BE, BF, CD, CE, CF.

Thus, you can use Distance Matrix API to determine the most effective routes of traveling between multiple staring and ending points and implement your own algorithms for solving routing problems.

Distance Matrix API returns only brief information about the route (distance and travel time). To get the full geometry of a route, use Directions API.

Move your mouse over a marker on the map to find out the distance and driving time to it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS Distance matrix API</title>
        <meta name="description" content="Several destination points example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
            #tooltip {
                padding: 12px 16px;
                background: #fff;
                box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
                border-radius: 4px;
                display: none;
                position: fixed;
                pointer-events: none;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <div id="tooltip"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script>
            const reqUrl = `https://routing.api.2gis.com/get_dist_matrix?key=Your directions API access key&version=2.0`;

            const map = new mapgl.Map('container', {
                center: [37.668598, 55.76259],
                zoom: 10,
                key: 'Your API access key',
            });

            function renderMarkersWithData(routes) {
                function generateTooltipText(index) {
                    const data = routes.find((item) => item.target_id === index);
                    if (!data) return undefined;
                    return `distance: ${data.distance.toLocaleString()} m.<br>by car: ${Math.round(
                        data.duration / 60,
                    )} min.`;
                }
                const tooltipEl = document.getElementById('tooltip');

                const startPoint = points.shift();
                const marker = new mapgl.Marker(map, {
                    coordinates: [startPoint.lon, startPoint.lat],
                    label: {
                        text: 'Point of departure',
                        fontSize: 13,
                    },
                });

                points.forEach((point, index) => {
                    const marker = new mapgl.Marker(map, {
                        coordinates: [point.lon, point.lat],
                        icon: 'https://docs.2gis.com/img/dotMarker.svg',
                    });
                    marker.on('mouseover', (event) => {
                        // Offset in pixels
                        const offset = 5;
                        tooltipEl.style.top = `${event.point[1] + offset}px`;
                        tooltipEl.style.left = `${event.point[0] + offset}px`;
                        tooltipEl.innerHTML = generateTooltipText(index + 1);
                        tooltipEl.style.display = 'block';
                    });
                    marker.on('mouseout', (e) => {
                        tooltipEl.style.display = 'none';
                    });
                });
            }

            const points = [
                {
                    lat: 55.716226,
                    lon: 37.729171,
                },
                {
                    lat: 55.723976,
                    lon: 37.624403,
                },
                {
                    lat: 55.71893,
                    lon: 37.564967,
                },
                {
                    lat: 55.730375,
                    lon: 37.483024,
                },
            ];

            fetch(reqUrl, {
                method: 'POST',
                body: JSON.stringify({
                    points,
                    sources: [0],
                    targets: [1, 2, 3],
                    mode: 'driving',
                    start_time: new Date().toISOString(),
                }),
            })
                .then((res) => res.json())
                .then((parsed) => renderMarkersWithData(parsed.routes))
                .catch((err) => console.error('error', err));
        </script>
    </body>
</html>

Distance Matrix API supports two modes of operation:

  • Calculating requests that contain up to 25 starting or ending points in synchronous mode. In this mode, the request returns the result of calculation.
  • Calculating requests that contain up to 1000 starting or ending points in asynchronous mode. In this mode, the request returns the task ID, which should be used to periodically check if the calculation is complete (see Large number of points).

Usage of this API requires an API key. To obtain the key:

  1. Sign in to the Platform Manager.
  2. Create a demo key (if you have not used Urbi products before) or request a production key: follow the link to contact a manager on the API Keys tab.

In the Platform Manager, you can also:

  • See information on your current keys: which services are enabled, which limit is set for each, when a key will be deactivated, and more.
  • Set restrictions for a key by HTTP headers or by IP and subnet.
  • Check the statistics of request distribution for each key.

To get the information about a route, send a POST request to the /get_dist_matrix endpoint. Specify your API key as the key parameter in the query string. Additionally, specify the required API version as the version parameter (2.0 by default).

https://routing.api.2gis.com/get_dist_matrix?key=API_KEY&version=2.0

Coordinates for the route and other parameters must be sent as a JSON string in the request body.

You can specify several starting and end points in the request body. For each specified starting point, a route will be built to each specified end point.

For example, to build routes for two starting points and two end points, send the following request:

curl --request POST \
 --url 'https://routing.api.2gis.com/get_dist_matrix?key=API_KEY&version=2.0' \
 --header 'Content-Type: application/json' \
 --data '{
    "points": [
        {
            "lat": 54.99770587584445,
            "lon": 82.79502868652345
        },
        {
            "lat": 54.99928130973027,
            "lon": 82.92137145996095
        },
        {
            "lat": 55.04533538802211,
            "lon": 82.98179626464844
        },
        {
            "lat": 55.072470687600536,
            "lon": 83.04634094238281
        }
    ],
    "sources": [0, 1],
    "targets": [2, 3]
}'

The points parameter is an array of route points. The sources and targets parameters are arrays of indices that determine which points of the points array are starting and end points, respectively.

Caution!

This query works with the following restrictions:

  • The number of points in the sources array or in the targets array does not exceed 25.
  • The distance between points does not exceed 2000 km in a straight line.

If at least one of these restrictions is not satisfied, the request will return an error. To make requests with this input data, use the asynchronous method.

For each pair of starting and ending points, the request will return route information including the route length in meters (distance) and travel time in seconds (duration). The point indices will be specified in the source_id and target_id fields. If a route could not be built for a particular pair of points, the status field will contain the string "FAIL".

More detailed information about response fields can be found in API Reference.

{
    "generation_time": 3349,
    "routes": [
        {
            "distance": 11287,
            "duration": 1319,
            "source_id": 0,
            "status": "OK",
            "target_id": 2
        },
        {
            "distance": 3839,
            "duration": 603,
            "source_id": 0,
            "status": "OK",
            "target_id": 3
        },
        {
            "distance": 12245,
            "duration": 1094,
            "source_id": 1,
            "status": "OK",
            "target_id": 2
        },
        {
            "distance": 11418,
            "duration": 931,
            "source_id": 0,
            "status": "OK",
            "target_id": 3
        }
    ]
}

By default, the server returns the shortest car route in time using current traffic data. To build a specific type of route, set the type parameter in the request.

{
    "points": [...],
    "type": "jam" // car route using current traffic data
}

Instead of current traffic data, you can build a route using statistical traffic data. To do this, specify the statistics route type and the required date and time in RFC 3339 format as the start_time parameter.

{
    "points": [...],
    "type": "statistics", // car route using statistical traffic data...
    "start_time": "2020-05-15T15:52:01Z"    // ...as of 15 May 2020, 15:52:01 UTC
}

To build the shortest route in distance, even if it is not optimal due to traffic jams, specify the shortest route type.

{
    "points": [...],
    "type": "shortest" // car route ignoring traffic
}

To build a cargo route, use the mode parameter with tha value truck.

The building of a cargo route is supported in synchronous mode only (no more than 25 starting or ending points).

{
    "points": [...],
    "mode": "truck" // cargo transport
}

You can also include public transport lanes when building a car route, which can be useful for taxi and bus routes. To do this, add the mode parameter with the value taxi.

{
    "points": [...],
    "mode": "taxi", // car route including public transport lanes...
    "type": "shortest" // ...and ignoring traffic
}

To build a pedestrian route, use the mode parameter with the value walking.

{
    "points": [...],
    "mode": "walking" // pedestrian route
}

To build a bicycle route, use the mode parameter with the value bicycle.

{
    "points": [...],
    "mode": "bicycle" // bicycle route
}

When building a route, you can exclude certain types of roads, such as toll roads or dirt roads, using the filters parameter, and exclude specific areas using the exclude parameter. For more information on using these parameters, see the corresponding sections of Directions API.

By default, responses are in the JSON format. To get a response in the Protocol Buffers format, specify the response_format=protobuf parameter in the query string:

https://routing.api.2gis.com/get_dist_matrix?key=API_KEY&version=2.0&response_format=protobuf

A schema of the protobuf format is available at DistanceMatrix.proto.

⚠ This functionality is currently in beta. To learn more about terms of use, email us at api@2gis.com

When using a large number of starting or ending points (more than 25), you need to use the asynchronous approach:

  1. Create a route building task.
  2. Periodically check the status of the task until the route calculation is complete.
  3. Get the calculated route when the task is complete.

To create a task, you need to send a POST request to the /async_matrix/create_task/get_dist_matrix. Specify your API key as the key parameter in the query string. Additionally, specify the required API version as the version parameter (2.0 by default).

https://routing.api.2gis.com/async_matrix/create_task/get_dist_matrix?key=API_KEY&version=2.0

Coordinates for the route and other parameters must be sent as a JSON string in the request body.

For example, to build routes for two starting points and two end points, send the following request:

curl --request POST \
 --url 'https://routing.api.2gis.com/async_matrix/create_task/get_dist_matrix?key=API_KEY&version=2.0' \
 --header 'Content-Type: application/json' \
 --data '{
    "points": [
        {
            "lat": 54.99770587584445,
            "lon": 82.79502868652345
        },
        {
            "lat": 54.99928130973027,
            "lon": 82.92137145996095
        },
        {
            "lat": 55.04533538802211,
            "lon": 82.98179626464844
        },
        {
            "lat": 55.072470687600536,
            "lon": 83.04634094238281
        }
    ],
    "sources": [0, 1],
    "targets": [2, 3]
}'

The request will return information about the created task, including the task identifier (task_id), which should be used to check the task status.

{
    "task_id": "TASK_ID",
    "status ": "TASK_CREATED"
}

To check the status of the task, send a GET request to the /async_matrix/result/get_dist_matrix/{task_id}?key=API_KEY endpoint, where task_id is the identifier of the created task.

curl --request GET \
  --url    'https://routing.api.2gis.com/async_matrix/result/get_dist_matrix/TASK_ID?key=API_KEY' \
  --header 'accept: application/json'

The request will return the current status of the task and a link to the solution file if the task has been completed successfully. The structure of the solution file is identical to the structure of a response to a synchronous request.

{
    // Task identifier.
    "task_id": "TASK_ID",
    // Task status.
    "status": "TASK_DONE",
    // Status code.
    "code": 200,
    // Additional information about the task status.
    "message": "start_time_ms=16516816106601123 calc_time_ms=14419 attract_time=4 build_time=28 points_count=3 source_count=1 target_count=2",
    // Link to the solution file.
    "result_link": "http://storage_host:port/dm/TASK_ID.response.json"
}

Tasks can have the following statuses:

  • TASK_CREATED - task has been created.
  • TASK_IN_QUEUE - task is in a queue, waiting to be processed.
  • TASK_IN_PROGRESS - task is being processed.
  • TASK_DONE - task was completed.
  • TASK_CANCELED - task was cancelled (see the message field for more details).