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.

Using Distance Matrix API, you can find points with the required time to reach and use this information to 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://catalog.api.2gis.com/get_dist_matrix?key=Your directions API access key`;

            const map = new mapgl.Map('container', {
                center: [55.26553, 25.23399],
                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: 25.16184629215101,
                    lon: 55.288509640285845,
                },
                {
                    lat: 25.2395871098727,
                    lon: 55.340674378221166,
                },
                {
                    lat: 25.32097657667498,
                    lon: 55.39079344410564,
                },
                {
                    lat: 25.32097657667498,
                    lon: 55.521205293543126,
                },
            ];

            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>

Usage of this API requires an API key. To obtain the key, fill out the form at dev.2gis.com/order.

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.

https://catalog.api.2gis.com/get_dist_matrix?key=API_KEY

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://catalog.api.2gis.com/get_dist_matrix?key=API_KEY' \
 --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.

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
}

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.