Навигация | Distance Matrix API | Примеры | 2GIS Documentation

Примеры

Наведите курсор на метку на карте, чтобы узнать расстояние и время езды до неё на автомобиле от точки отправления.

<!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: [82.795, 55.04],
                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 `расстояние: ${data.distance.toLocaleString()} м.<br>ехать на машине: ${Math.round(
                        data.duration / 60,
                    )} мин.`;
                }
                const tooltipEl = document.getElementById('tooltip');

                const startPoint = points.shift();
                const marker = new mapgl.Marker(map, {
                    coordinates: [startPoint.lon, startPoint.lat],
                    label: {
                        text: 'Точка отправления',
                        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: 54.99770587584445,
                    lon: 82.79502868652345,
                },
                {
                    lat: 54.99928130973027,
                    lon: 82.92137145996095,
                },
                {
                    lat: 55.04533538802211,
                    lon: 82.98179626464844,
                },
                {
                    lat: 55.072470687600536,
                    lon: 83.04634094238281,
                },
            ];

            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>