Navigation | TSP API | Overview | 2GIS Documentation

TSP API

The TSP API allows you to solve the Travelling salesman problem, that is to find the shortest route (by distance) to visit all the points selected on the map.


Requests are made using the POST method, all required parameters should be passed in the JSON format. The responses are also generated in the JSON format.

The request takes the coordinates of the route points. You will get the length and the travel time for the route as well as for each part of it in the response. All request and response parameters are listed in the API Reference.

Building the optimal route from the starting point through all the points on the map.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>2GIS TSP API</title>
        <meta name="description" content="Traveling salesman issue example" />
        <style>
            html,
            body,
            #container {
                margin: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
            #go {
                padding: 4px 10px;
                background: #00a81f;
                border-radius: 4px;
                box-shadow: 0 1px 3px 0 rgba(38, 38, 38, 0.5);
                border: none;
                color: #fff;
                font-size: 12px;
                min-width: 215px;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <div id="tooltip"></div>
        <script src="https://mapgl.2gis.com/api/js/v1"></script>
        <script src="https://unpkg.com/@2gis/mapgl-directions@^1/dist/directions.js"></script>

        <script>
            const naviApiKey = 'Your directions API access key';
            const reqUrl = `https://catalog.api.2gis.com/get_tsp?key=${naviApiKey}`;
            const start = {
                lat: 54.97564330524832,
                lon: 82.88566589362209,
            };
            const checkpoints = [
                {
                    lat: 54.96697254872909,
                    lon: 82.90489196787385,
                },
                {
                    lat: 55.015032246347914,
                    lon: 82.97904968269394,
                },
                {
                    lat: 55.00085668167925,
                    lon: 82.86369323731246,
                },
                {
                    lat: 54.99731200769605,
                    lon: 82.97149658168925,
                },
                {
                    lat: 54.99928130973027,
                    lon: 82.92137145996095,
                },
            ];

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

            // рисуем маркеры точек назначения
            checkpoints.forEach((point, index) => {
                const marker = new mapgl.Marker(map, {
                    coordinates: [point.lon, point.lat],
                    icon: 'https://docs.2gis.com/img/dotMarker.svg',
                });
            });

            // рисуем маркер точки отправления
            const startMarker = new mapgl.Marker(map, {
                coordinates: [start.lon, start.lat],
                label: {
                    text: 'точка отправления',
                    fontSize: 13,
                },
            });

            const controlsHtml = `<button id="go">Построить оптимальный маршрут</button> `;
            new mapgl.Control(map, controlsHtml, {
                position: 'topLeft',
            });
            const goButton = document.getElementById('go');

            goButton.addEventListener('click', function() {
                goButton.disabled = true;
                goButton.textContent = 'Строим маршрут...';
                buildRoute();
            });

            const directions = new mapgl.Directions(map, {
                // This key can be used for demo purpose only!
                // You can get your own key on http://partner.api.2gis.ru/
                directionsApiKey: naviApiKey,
            });

            function buildRoutePointsSequence(routes) {
                const firstRoutePoint = checkpoints[routes[0].start_id];
                // добавляем точку изначального местоположения и первую точку маршрута
                const points = [
                    [start.lon, start.lat],
                    [firstRoutePoint.lon, firstRoutePoint.lat],
                ];

                for (const route of routes) {
                    const target = checkpoints[route.target_id];
                    points.push([target.lon, target.lat]);
                }

                return points;
            }

            function buildRoute() {
                fetch(reqUrl, {
                    method: 'POST',
                    body: JSON.stringify({
                        start,
                        checkpoints,
                        start_time: new Date().toISOString(),
                    }),
                })
                    .then((res) => res.json())
                    .then((parsed) => {
                        // рисуем геометрию построенного маршрута
                        directions.carRoute({
                            points: buildRoutePointsSequence(parsed.routes),
                        });
                        goButton.textContent = 'Маршрут построен';
                    })
                    .catch((err) => console.error('error', err));
            }
        </script>
    </body>
</html>

To retrieve route data, make a POST request to https://catalog.api.2gis.com/get_tsp?key=YOUR_KEY with Content-Type application/json.

The request takes the following parameters:

  • key=YOUR_KEY — your API key
{
    "start": {
        "lat": 54.998493600520156,
        "lon": 82.65769958496095
    },
    "finish": {
        "lat": 55.05516914322075,
        "lon": 83.15208435058594
    },
    "checkpoints": [
        {
            "lat": 54.99770587584445,
            "lon": 82.79502868652345
        },
        {
            "lat": 54.99928130973027,
            "lon": 82.92137145996095,
            "delay": 300
        },
        {
            "lat": 55.04533538802211,
            "lon": 82.98179626464844
        },
        {
            "lat": 55.072470687600536,
            "lon": 83.04634094238281
        }
    ],
    "start_time": "2020-04-26T07:05:30Z"
}
{
  "finish": {},
  "generation_time": 1.226999998092651,
  "mode": "driving",
  "routes": [
    {
      "distance": 1851,
      "duration": 226,
      "geometry": [...],
      "start_id": 0,
      "target_id": 1,
      "wkt": "LINESTRING(...)"
    },
    {
      "distance": 941,
      "duration": 127,
      "geometry": [...],
      "start_id": 1,
      "target_id": 2,
      "wkt": "LINESTRING(...)"
    }
  ],
  "start": {
    "distance": 1112,
    "duration": 107,
    "geometry": [...],
    "target_id": 0,
    "wkt": "LINESTRING(...)"
  },
  "status": "OK",
  "total_distance": 4597,
  "total_duration": 636
}
  1. To get your API access key, fill in the application form.
  2. Learn about the request and response formats.