Time vs Distance Routing

Route by shortest time or by shortest distance
<!DOCTYPE html>
<html>
<head>
    <!--  Include targomo webfonts -->
    <link rel="stylesheet" href="https://releases.targomo.com/tgm-icons/webfont/tgm-icon.css">
    <!--  Include leaflet javascript and css -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css">
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet-src.js" crossorigin=""></script>
    <!--  Include targomo leaflet full build -->
    <script src="https://releases.targomo.com/leaflet/latest-full.min.js"></script>
    <style>
        body, html, #map {
            margin: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
        }
        .markers {
            position: fixed;
            top: 10px;
            right: 10px;
        }
        .marker-container {
            padding: 4px 6px;
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: 2px solid rgba(0, 0, 0, 0.2);
            background-clip: padding-box;
            border-radius: 4px;
            margin-bottom: 6px;
        }
        .marker-container.active {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <!--  where the map will live  -->
    <div id="map"></div>
    <!--  selector used to change the routing mode  -->
    <div class="markers">
        <div onclick="setMode('time')" id="btn-time" class="marker-container active" title="union">
            <span class="tgm-icon tgm-ux-time"></span>
        </div>
        <div onclick="setMode('distance')" id="btn-distance" class="marker-container" title="average">
            <span class="tgm-icon tgm-ux-distance"></span>
        </div>
    </div>
    <script>
        // create targomo client
        const client = new tgm.TargomoClient('westcentraleurope', '__targomo_key_here__');
        
        // Create a Leaflet map with basemap, set the center of the map to Portland, Oregon.
        const tileLayer = new tgm.leaflet.TgmLeafletTileLayer(client, 'Light');
        var map = L.map('map', {
            layers: [tileLayer],
            scrollWheelZoom: false
        }).setView([46.80320, 7.15120], 13);
        
        // set the attribution
        const attributionText = '<a href="https://www.targomo.com/developers/resources/attribution/" target="_blank">&copy; Targomo</a>';
        map.attributionControl.addAttribution(attributionText);
        
        // create a target marker icon to be able to distinguish source and target markers
        const redIcon = L.icon({
            iconUrl: '__base_url__images/code-example/marker-icon-red.png',
            shadowUrl: '__base_url__images/code-example/marker-shadow.png',
            iconAnchor: [12, 45],
            popupAnchor: [0, -35]
        });
        
        // create a draggable source and target marker add them to the map
        const sourceMarker = L.marker(
            [46.80320, 7.15120], 
            { draggable: true }
        ).addTo(map);
        
        const targetMarker = L.marker(
            [46.68267, 7.85162], 
            { icon: redIcon, draggable: true }
        ).addTo(map);
        
        // Every time a marker is dragged, update the location and request a new route.
        sourceMarker.on("dragend", (e) => refreshRoutes());
        targetMarker.on("dragend", (e) => refreshRoutes());
        
        // The travel options used to determine which routes should be searched for
        const options = {
            travelType: 'car',
            maxEdgeWeight: 5400,
            edgeWeight: 'time',
            pathSerializer: 'compact'
        };
        
        // Routes Layers
        let leafletLayers = new L.FeatureGroup();
        leafletLayers.addTo(map);
        
        // Requesting routs from the Targomo API.
        function refreshRoutes() {
            const source = [{...sourceMarker.getLatLng(), ...{ id: 'source' }}];
            const target = [{...targetMarker.getLatLng(), ...{ id: 'target' }}];
        
            client.routes.fetch(source, target, options).then(result => {
                // clear out popups
                targetMarker.closePopup().unbindPopup();
                // Remove all old layers
                leafletLayers.clearLayers();
        
                if (result.length > 0) {
                    // Go through the result, draw a solid line for all the route
                    result.forEach((route) => {
                        route.routeSegments.forEach(segment => {
                            const leafletPoints = segment.points.map(point => new L.LatLng(point.lat, point.lng));
                            leafletLayers.addLayer(new L.Polyline(leafletPoints, {
                                color: '#FF8319',
                                weight: 5,
                                opacity: 1,
                                smoothFactor: 1
                            }))
                        })
                    });
        
                    map.fitBounds(leafletLayers.getBounds(), { padding: [20,20] }); // zoom to it
                } else {
                    const message = options.edgeWeight === 'time' ? `90 minutes` : `120 km`
                    targetMarker
                        .bindPopup(`no route found within ${message}`, { autoClose: false })
                        .openPopup();
                }
            });
        }
        
        // Update the route each time the selection is updated.
        function setMode(mode) {
            const selector = `btn-${mode}`;
            document.getElementsByClassName('active')[0].classList.remove('active');
            document.getElementById(selector).classList.add('active');
            options.edgeWeight = mode;
            options.maxEdgeWeight = mode === 'time' ? 5400 : 120000;
            refreshRoutes();
        }
        
        // Request routes once immediately on page load.
        refreshRoutes();
    </script>
</body>
</html>
content_copy
Copied to clipboard