Navigation | Routing API | Overview | Urbi Documentation
Routing APInew

Overview

Routing API helps you plot one or multiple routes on the map for transport or walking. An interactive example below shows building a route for a car:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>2GIS Routing API</title>
    <meta name="description" content="Building routes via the Routing API" />
    <style>
        html,
        body,
        #container {
            margin: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .controls {
            position: absolute;
            top: 10px;
            left: 10px;
        }

        .controls button {
            padding: 5px 10px;
            font-size: 14px;
            border: none;
            border-radius: 5px;
            background-color: #0078FF;
            color: white;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
        }

        .controls button:disabled {
            background: #f2f2f2;
            color: #6e6d6d;
            cursor: not-allowed;
        }
    </style>
</head>

<body>
    <div id="container"></div>
    <div class="controls">
        <button id="resetButton" disabled>Click two points on the map</button>
    </div>
    <script src="https://mapgl.2gis.com/api/js/v1"></script>
    <script>
        const reqUrl = `https://routing.api.2gis.com/routing/7.0.0/global?key=Your directions API access key`;

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

        const markers = [];
        let firstPoint = null;
        let secondPoint = null;
        let routeLine = null;
        let selecting = 'a';
        const resetButton = document.getElementById('resetButton');

        resetButton.addEventListener('click', () => {
            selecting = 'a';
            firstPoint = null;
            secondPoint = null;
            if (routeLine) routeLine.destroy();
            markers.forEach((marker) => marker.destroy());
            markers.length = 0;
            resetButton.disabled = true;
            resetButton.textContent = 'Click two points on the map';
        });

        map.on('click', (event) => {
            if (!event || !event.lngLat || !Array.isArray(event.lngLat) || event.lngLat.length !== 2) {
                console.error("Invalid click event: lngLat is undefined or invalid");
                return;
            }

            const [lng, lat] = event.lngLat;

            console.log(`Clicked coordinates: ${lng}, ${lat}`);

            if (selecting !== 'end') {
                const marker = new mapgl.Marker(map, {
                    coordinates: [lng, lat],
                    icon: 'https://docs.2gis.com/img/dotMarker.svg',
                });
                markers.push(marker);
            }

            if (selecting === 'a') {
                firstPoint = { lon: lng, lat: lat };
                selecting = 'b';
            } else if (selecting === 'b') {
                secondPoint = { lon: lng, lat: lat };
                selecting = 'end';
            }

            if (firstPoint && secondPoint) {
                fetchRoute([firstPoint, secondPoint]);

                resetButton.disabled = false;
                resetButton.textContent = 'Reset points';
            }
        });

        function fetchRoute(points) {
            fetch(reqUrl, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    points,
                    locale: "ru",
                    transport: "driving",
                    filters: ["dirt_road", "toll_road", "ferry"],
                    output: "detailed"
                })
            })
                .then((res) => {
                    if (!res.ok) {
                        throw new Error(`HTTP error! Status: ${res.status}`);
                    }
                    return res.json();
                })
                .then((parsed) => {
                    if (parsed.result && parsed.result.length > 0) {
                        const coordinates = parsed.result[0].maneuvers
                            .flatMap((maneuver) => {
                                if (
                                    maneuver.outcoming_path &&
                                    maneuver.outcoming_path.geometry &&
                                    maneuver.outcoming_path.geometry.length > 0
                                ) {
                                    return maneuver.outcoming_path.geometry
                                        .flatMap((geometry) => {
                                            const selection = geometry.selection;
                                            return selection
                                                .replace("LINESTRING(", "")
                                                .replace(")", "")
                                                .split(",")
                                                .map((point) => point.trim().split(" ").map(Number));
                                        });
                                }
                                return [];
                            });

                        if (coordinates.length > 0) {
                            renderRoute(coordinates);
                        } else {
                            console.error("No coordinates found in response");
                        }
                    } else {
                        console.error("No route found in response");
                    }
                })
                .catch((err) => console.error("Error fetching route data:", err.message || err));
        }

        function renderRoute(coordinates) {
            if (routeLine) {
                routeLine.destroy();
            }
            routeLine = new mapgl.Polyline(map, {
                coordinates,
                width: 6,
                color: "#0078FF",
            });
        }

        fetchRoute();
    </script>
</body>

</html>

To edit the example code, select Source code and then Edit on Codepen.

You can also work with Routing API in the playground (no authorization needed).


For each route, you can obtain:

  • Length, travel time, and full geometry.
  • Elevation change along the route.
  • Information about special points on the route, such as the start of a toll road.

You can consider the following parameters when building routes, depending on the selected transport type:

  • Real-time traffic (with regular updates) or statistically predicted congestion.
  • Road closures (considered by default, can be forcibly ignored).
  • Public transport lanes for taxis and emergency services.
  • Different road types.
  • Pedestrian crossings, stairways, and detours.
  • Exclusion of a specific area.
  • Weight, dimensions, and sign restrictions for trucks.

For more information about route parameters, see API Reference.

  • Up to 10 waypoints, including the start and finish points for cars and trucks.
  • Up to 5 waypoints, including the start and finish points for pedestrian routes.
  • Up to 50 pairs of points when building multiple routes in one request (using intermediate points is not supported).

Truck routing is available in the following countries:

  • Azerbaijan
  • Armenia
  • Belarus
  • Georgia
  • Kazakhstan
  • Russia
  • Uzbekistan
  • United Arab Emirates

Routing for emergency services is available in the following countries:

  • Oman
  • Saudi Arabia
  • United Arab Emirates
  • When building a route for one set of points (including intermediate points), the number of requests is charged. Building alternative routes is not charged additionally.
  • When building multiple routes for a set of point pairs, calculations for each pair of points are charged. For example, if you specify 5 arrays of point pairs (points field) in one request, 5 calculations are charged.