Leaflet Routing API

Drag the source and targets to see the re-routing
<!DOCTYPE html>
<html>

<head>
    <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 {
            margin: 0;
            width: 100%;
            height: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <!--  where the map will live  -->
    <div id="map"></div>
    <script>
        // create targomo client
        const client = new tgm.TargomoClient('northamerica', '__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([45.494435, -122.651968], 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 two draggable target markers, add them to the map
        const sourceMarker = L.marker([45.497804, -122.676429], { draggable: true }).addTo(map);
        const targetMarkers = [
            L.marker([45.514286, -122.641754], { icon: redIcon, draggable: true }).addTo(map),
            L.marker([45.478429, -122.617893], { icon: redIcon, draggable: true }).addTo(map)
        ]
        
        targetMarkers.forEach(m => m.on("dragend", (e) => refreshRoutes()));
        
        // Every time a marker is dragged, update the location and request a new route.
        sourceMarker.on("dragend", (e) => refreshRoutes());
        
        // The travel options used to determine which routes should be searched for
        const options = {
            travelType: 'transit',
            maxEdgeWeight: 3600,
            edgeWeight: 'time',
            pathSerializer: 'compact',
            transitFrameDate: 20190219,
            transitFrameTime: 36000,
            transitFrameDuration: 3600,
            transitMaxTransfers: 5
        };
        
        // This array is to keep track of all the leaflet layers which should be removed from the map each time new routes are fetched.
        let leafletLayers = [];
        
        // Requesting routs from the Targomo API.
        function refreshRoutes() {
            const source = [{...sourceMarker.getLatLng(), ...{ id: 'source' }}];
            const targets = targetMarkers.map((t,i) => ({...t.getLatLng(), ...{ id: i }}));
            client.routes.fetch(source, targets, options).then(result => {
                // clear out popups
                targetMarkers.forEach(t => t.closePopup().unbindPopup());
                
                // Remove all old layers
                leafletLayers.forEach(layer => map.removeLayer(layer));
        
                leafletLayers = [];
        
                // Go through the result, draw a dotted line for all parts of the route which are walked,
                // draw a solid line for the parts of the route which are traveled with transit
                // and finally draw circles for each transfer.
                if (result.length > 0) {
                    let circlePoints = [];
                    result.forEach((route) => {
                        route.routeSegments.forEach(segment => {
                            const leafletPoints = segment.points.map(point => new L.LatLng(point.lat, point.lng));
                            if (segment.type === "WALK") {
                                drawDottedLine(leafletPoints);
                            } else if (segment.type === "TRANSIT") {
                                drawSolidLine(leafletPoints);
                            } else if (segment.type === "TRANSFER") {
                                circlePoints = circlePoints.concat(leafletPoints);
                            }
                        })
                    });
                    // The circles are drawn after the lines so that they appear on top of the lines.
                    drawCircles(circlePoints);
                }
        
                targets.forEach(t => {
                    // notify if route not found
                    if (!result.find(r => +r.targetId === t.id)) {
                        targetMarkers[t.id].bindPopup(`no route found within 1 hour`,{autoClose: false}).openPopup();
                    }
                });
            });
        }
        
        function drawDottedLine(leafletPoints) {
            const line = new L.Polyline(leafletPoints, {
                color: '#3F51B5',
                weight: 5,
                opacity: 1,
                smoothFactor: 1,
                dashArray: '5, 10'
            });
            line.addTo(map);
            leafletLayers.push(line);
        }
        function drawSolidLine(leafletPoints) {
            const line = new L.Polyline(leafletPoints, {
                color: '#FF5722',
                weight: 5,
                opacity: 1,
                smoothFactor: 1
            });
            line.addTo(map);
            leafletLayers.push(line);
        }
        function drawCircles(leafletPoints) {
            leafletPoints.forEach(point => {
                const circle = L.circle(point, {
                    radius: 1,
                    weight: 15,
                    color: '#8BC34A'
                });
                circle.addTo(map);
                leafletLayers.push(circle);
            });
        }
        
        // Request routes once immediately on page load.
        refreshRoutes();
    </script>
</body>
content_copy
Copied to clipboard