Leaflet Polygons with Custom Colors
<!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%;
        }

        #color-mode-select {
            position: absolute;
            z-index: 400;
            top: 10px;
            right: 10px;
            font-family: 'Open Sans', sans-serif;
        }
    </style>
</head>

<body>
    <!--  where the map will live  -->
    <div id="map"></div>
    <!--  selector used to change the intersection mode  -->
    <select id="color-mode-select" onchange="switchmode(this);"></select>
    <script>
        const select = document.querySelector("#color-mode-select");
        
        // create targomo client
        const client = new tgm.TargomoClient('westcentraleurope', '__targomo_key_here__');
        
        // Define the stops and colors which can be used to construct the returned polygon.
        // In this example, all values of the result between 0 and 300 (0 and 5 minutes) will have the color associated with "300"
        // Values on the outer edge of the returned polygon (i.e. between 1500 and 1800, or 25 and 30 minutes) will have the color associated with 1800
        const colorModes = [
            { text: 'Standard', value: "standard", data: { 300: '#006837', 600: '#39B54A', 900: '#8CC63F', 1200: '#F7931E', 1500: '#F15A24', 1800: '#C1272D' } },
            { text: 'Color blind', value: "colorblind", data: { 300: '#4575b4', 600: '#91bfdb', 900: '#e0f3f8', 1200: '#fee090', 1500: '#fc8d59', 1800: '#d73027' } },
            { text: 'Print & Photocopy safe', value: "print", data: { 300: '#d7191c', 600: '#fdae61', 900: '#ffffbf', 1200: '#abdda4', 1500: '#2b83ba', 1800: '#B74A85' } },
        ];
        
        for (let mode of colorModes) {
            let option = document.createElement("option");
            option.text = mode.text;
            option.value = mode.value;
            select.appendChild(option);
        }
        
        // Create a Leaflet map with basemap, set the center of the map to the city center of Utrecht.
        const tilesUrl = 'https://api.maptiler.com/maps/positron/{z}/{x}/{y}@2x.png?key=__your_maptiler_api_key__';
        const tileLayer = L.tileLayer(tilesUrl, {
            tileSize: 512, zoomOffset: -1,
            minZoom: 1, crossOrigin: true
        });
        var map = L.map('map', {
            layers: [tileLayer],
            scrollWheelZoom: false
        }).setView([52.097598, 5.125778], 14);
        const attributionText = `<a href="https://www.targomo.com/developers/resources/attribution/" target="_blank">&copy; Targomo</a>`;
        map.attributionControl.addAttribution(attributionText);
        
        // Define source locations which are passed into the Targomo polygon service.
        const sources = [{ id: 1, lat: 52.102816, lng: 5.100517 }, { id: 2, lat: 52.095334, lng: 5.137219 }];
        
        // Add markers for the sources on the map.
        sources.forEach(source => {
            L.marker([source.lat, source.lng]).addTo(map)
        });
        
        // Set the traveloptions and options for the polygon service here. The 'intersectionMode' option will be changed everytime the selection is updated.
        const options = {
            travelType: 'bike',
            maxEdgeWeight: 1800,
            edgeWeight: 'time',
            travelEdgeWeights: Object.keys(colorModes[0].data),
            srid: 4326,
            simplify: 200,
            serializer: 'json',
            intersectionMode: 'union'
        };
        
        // Using the Leaflet extension we can easily visualize the returned polygons on a Leaflet map.
        const polygonOverlayLayer = new tgm.leaflet.TgmLeafletPolygonOverlay();
        polygonOverlayLayer.addTo(map);
        polygonOverlayLayer.setColors(colorModes[0].data);
        polygonOverlayLayer.setStrokeWidth(20)
        
        // Requesting polygons from the Targomo API.
        function refreshPolygons() {
            client.polygons.fetch(sources, options).then((result) => {
                polygonOverlayLayer.setData(result);
                // calculate bounding box for polygons
                const bounds = result.getMaxBounds();
                // zoom to the polygon bounds
                map.fitBounds(new L.latLngBounds(bounds.northEast, bounds.southWest));
            });
        }
        
        // Update the colors each time the selection is updated.
        function switchmode(v) {
            polygonOverlayLayer.setColors(colorModes.find(mode => mode.value === v.value).data);
        }
        
        // Request polygons once immediately on page load.
        refreshPolygons();
    </script>
</body>
content_copy
Copied to clipboard