Routing in Leaflet
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>
    <script src="https://unpkg.com/@targomo/core" ></script>
    <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 one of our basemaps, set the center of the map to Portland, Oregon.
        const tileLayer = new tgm.leaflet.TgmLeafletTileLayer(client, 'Toner', {})
        var map = L.map('map', {
            layers: [tileLayer],
            scrollWheelZoom: false
        }).setView([45.494435398006495, -122.65196800231935], 13);

        // set the attribution
        const attributionText = `<a href='https://www.openstreetmap.org/copyright' target='_blank'>&copy; OpenStreetMap contributors</a> <a href='http://openmaptiles.org/' target='_blank'>&copy; OpenMapTiles</a> <a href='https://targomo.com/developers/attribution/' target='_blank'>&copy; Targomo</a>`
        map.attributionControl.addAttribution(attributionText);

        // Define source and target locations which are passed into the Targomo routing service.
        let targets = [
            {id: 1, lat: 45.5142865031511, lng: -122.64175415039064},
            {id: 2, lat: 45.47842910891348, lng: -122.61789321899415}
        ];
        let source = {id: 0, lat: 45.49780456353945, lng: -122.67642974853517};

        // create a target marker icon to be able to distinguish source and target markers
        const redIcon = L.icon({
            iconUrl: 'https://targomo.com/developers/images/code-example/marker-icon-red.png',
            shadowUrl: 'https://targomo.com/developers/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([source.lat, source.lng], { draggable : true }).addTo(map);
        const targetMarker1 = L.marker([targets[0].lat, targets[0].lng], { icon: redIcon, draggable : true }).addTo(map);
        const targetMarker2 = L.marker([targets[1].lat, targets[1].lng], { icon: redIcon, draggable : true }).addTo(map);

        // Everytime a marker is dragged, update the location and request a new route.
        sourceMarker.on("dragend", markerDragged(source.id));
        targetMarker1.on("dragend", markerDragged(targets[0].id));
        targetMarker2.on("dragend", markerDragged(targets[1].id));
        function markerDragged(id) {
            return (e) => {
                const position = e.target.getLatLng();
                if (id === source.id) {
                    source = {id: source.id, lat: position.lat, lng: position.lng};
                } else {
                    targets = targets.map(target => target.id === id ? {id: id, lat: position.lat, lng: position.lng} : target);
                }
                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() {
            client.routes.fetch([source], targets, options).then(result => {

                // 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.
                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);
            });
        }

        function drawDottedLine(leafletPoints) {
            const line = new L.Polyline(leafletPoints, {
                color: '#3F51B5',
                weight: 5,
                opacity: 1,
                smoothFactor: 1,
                dashArray: '10, 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!