TSP API
TSP API позволяет решить задачу коммивояжёра — построить кратчайший по расстоянию маршрут обхода указанных точек на карте.
Как это работает
Запросы осуществляются методом POST, все необходимые параметры передаются в формате JSON. Ответы формируются в формате JSON.
В запросе передаются координаты точек маршрута. В ответ приходят длина и время в пути всего маршрута и каждой его части. Все параметры запроса и ответа приведены в Описании API.
Построение оптимального маршрута из начальной точки через все метки на карте.
<!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>
Пример запроса
Данные можно получить с помощью POST-запроса на URL https://catalog.api.2gis.com/get_tsp?key=YOUR_KEY
и payload'а с Content-Type application/json.
В запросе используются следующие параметры:
key=YOUR_KEY
— ваш ключ API.
{
"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
}
Начало работы
- Получите ключ доступа к API. Для этого заполните анкету.
- Посмотрите все параметры форматов запроса и ответа.