Skip to content

Routing Service

This example demonstrates how to display routing information on a map using the Routing API. Click on any location on the map to set waypoints and calculate the route between them. The routing information is displayed on the left side of the map.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <script src="https://cdn.smartmaps.cloud/packages/smartmaps/smartmaps-gl/v2/umd/smartmaps-gl.min.js"></script>
        <style>
            body {
                margin: 0;
                padding: 0;
                display: flex;
                /* Use flexbox to position the map and info side by side */
            }

            #map {
                flex: 1;
                /* Allow the map to take up remaining space */
                height: 100vh;
            }

            #reset-button {
                position: absolute;
                top: 3%;
                left: 50%;
                z-index: 1;
                transform: translateX(-50%);
                background-color: #18345c;
                color: white;
                border: none;
                padding: 10px 20px;
                cursor: pointer;
                border-radius: 4px;
            }

            #reset-button:hover {
                background-color: #0a5fa0;
            }

            #route-info {
                width: 300px;
                /* Fixed width for the route info panel */
                height: 100vh;
                /* Full viewport height */
                background-color: rgba(255, 255, 255, 0.8);
                overflow-y: auto;
                /* Allow scrolling if content overflows */
            }
        </style>
    </head>

    <body>
        <!-- Route info panel on the left -->
        <div id="route-info">Routing advice will be displayed once map points are set.</div>

        <!-- Map container -->
        <div id="map"></div>

        <button id="reset-button">Reset Waypoints</button>

        <script>
            const map = new smartmapsgl.Map({
                apiKey: 'INSERT API-KEY',
                container: 'map',
                center: { lat: 49.02164948779226, lng: 8.439330018049352 },
                zoom: 10,
                style: smartmapsgl.MapStyle.LIGHT
            });

            let waypoints = [];
            let markers = [];

            function removeMarkers() {
                markers.forEach((marker) => marker.remove());
                markers = [];
            }

            function removeRoute() {
                if (map.getLayer('route')) {
                    map.removeLayer('route');
                }
                if (map.getSource('route')) {
                    map.removeSource('route');
                }
            }

            function resetWaypoints() {
                waypoints = [];
                removeMarkers();
                removeRoute();
                document.getElementById('route-info').innerHTML = '';
            }

            document.getElementById('reset-button').addEventListener('click', resetWaypoints);

            map.on('click', async (event) => {
                const waypoint = {
                    longitude: event.lngLat.lng,
                    latitude: event.lngLat.lat
                };

                const marker = new smartmapsgl.Marker().setLngLat(event.lngLat).addTo(map);
                markers.push(marker);

                waypoints.push(waypoint);

                // Only calculate route if at least two waypoints are set
                if (waypoints.length < 2) return;

                try {
                    const features = waypoints.map(waypoint => ({
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [waypoint.longitude, waypoint.latitude]
                        },
                        properties: {}
                    }));

                    const response = await fetch(`https://www.yellowmap.de/api_rst/v2/geojson/route?apiKey=[INSERT_API-KEY]`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            type: 'FeatureCollection',
                            routingparams: {
                                type: 'ROUTE',
                                isoLocale: 'en-GB',
                                coordFormatOut: 'GEODECIMAL_POINT',
                                speedProfile: 'FAST',
                                routingTimeMode: 'ARRIVAL'
                            },
                            authentication: {
                                channel: ''
                            },
                            crs: {
                                type: 'name',
                                properties: {
                                    name: 'urn:ogc:def:crs:OGC:1.3:CRS84'
                                }
                            },
                            features
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`Server error: ${response.status}`);
                    }

                    const result = await response.json();

                    if (!result.features || result.features.length === 0) {
                        throw new Error("No route found");
                    }

                    const route = result.features[0];
                    const routeInfoDiv = document.getElementById('route-info');

                    // Extract and convert distance and duration
                    const distanceMeters = result.properties.distance;
                    const durationSeconds = result.properties.duration;

                    // Convert meters to kilometers
                    const distanceKm = (distanceMeters / 1000).toFixed(2);

                    // Convert seconds to hours and minutes
                    const hours = Math.floor(durationSeconds / 3600);
                    const minutes = Math.floor((durationSeconds % 3600) / 60);

                    // Display distance and duration
                    routeInfoDiv.innerHTML = `<strong>Distance:</strong> ${distanceKm} km<br><strong>Duration:</strong> ${hours} hours ${minutes} minutes<br><br>`;

                    // Add routing instructions
                    result.features.slice(1).forEach((feature) => {
                        const description = feature.properties.description;
                        routeInfoDiv.innerHTML += `${description}<br>`;
                    });

                    removeRoute();

                    map.addSource('route', {
                        type: 'geojson',
                        data: route
                    });
                    map.addLayer({
                        id: 'route',
                        type: 'line',
                        source: 'route',
                        layout: {
                            'line-join': 'round',
                            'line-cap': 'round'
                        },
                        paint: {
                            'line-color': '#0A5FA0',
                            'line-width': 8
                        }
                    });

                } catch (error) {
                    console.error("Error fetching route:", error);
                    alert("Failed to fetch route. Please try again.");
                }
            });
        </script>
    </body>
</html>