<!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@^2/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, {
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>