Maplibre-GL Routing API

Show Routing API results on a Maplibre-GL map
<!DOCTYPE html>
<html>
<head>
    <!--  Include maplibregl javascript and css -->
    <script src='https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js'></script>
    <link href='https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css' rel='stylesheet'>
    <!-- Include turf for view fitting -->
    <script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>

    <!--  Include targomo core -->
    <script src='https://releases.targomo.com/core/latest.min.js'></script>
    <style>
        body, html, #map {
            margin: 0; width: 100%; height: 100%;
        }
        #message {
            display: none; position: absolute;
            top: 0; background-color: #FF8319;
            color: white; z-index: 400; font-family: sans-serif;
            text-align: center; width: 100%; margin: 0px;
            padding-top: 10px; padding-bottom: 10px;
        }
        #message.visible {
            display: inline;
        }
    </style>
</head>
<body>
    <!--  where the map will live  -->
    <div id='map'></div>
    <div id="message">No routes found in under 1hr - try moving the pins</div>
    <script>
        // create targomo client
        const client = new tgm.TargomoClient('westcentraleurope', '__targomo_key_here__')
        // Coordinates to center the map
        const source = { lng: 4.335678, lat: 50.841535, id: 'source' }
        const target = { lng: 4.392892, lat: 50.840536, id: 'target' }
        
        // add the map and set the initial center to berlin
        const map = new maplibregl.Map({
            container: 'map',
            style: client.basemaps.getGLStyleURL('Light'),
            zoom: 13,
            center: target
        }).addControl(new maplibregl.NavigationControl())
        
        // disable scroll zoom
        map.scrollZoom.disable()
        
        // The travel options used to determine which routes should be searched for
        const options = {
            travelType: 'transit',
            maxEdgeWeight: 3600,
            edgeWeight: 'time',
            pathSerializer: 'geojson',
            // yes, 'polygon'... this comes from a legacy implementation when polygons were the only service. 
            // Will be changing in the future to a more generalized approach.
            polygon: {
                srid: 4326
            }
        }
        
        const emptyData = { 'type': 'FeatureCollection', 'features': [] }
        
        const sourceMarker = new maplibregl.Marker({ draggable: true })
            .setLngLat(source).addTo(map)
        const targetMarker = new maplibregl.Marker({ draggable: true, color: '#FF8319' })
            .setLngLat(target).addTo(map)
        
        //calculate new routes when either source or target moves
        sourceMarker.on('dragend', getRoute)
        targetMarker.on('dragend', getRoute)
        
        async function getRoute() {
            document.getElementById('message').classList.remove('visible')
            // Requesting routes from the Targomo API.
            const route = await client.routes.fetch(
                [{ ...sourceMarker.getLngLat(), ...{ id: source.id } }],
                [{ ...targetMarker.getLngLat(), ...{ id: target.id } }],
                options)
            if (route && route.length > 0) {
                // only one source-target supplied, so only one route returned
                map.getSource('route').setData(route[0])
                map.fitBounds(turf.bbox(route[0]), { padding: 20 })
            } else {
                // no routes found
                map.getSource('route').setData(emptyData)
                document.getElementById('message').classList.add('visible')
            }
        }
        
        map.on('load', () => {
            // add empty source
            map.addSource('route', {
                type: 'geojson',
                data: emptyData,
                attribution: '<a href="https://www.targomo.com/developers/resources/attribution/" target="_blank">&copy; Targomo</a>'
            })
            
            map.addLayer({
                id: 'route',
                type: 'line',
                source: 'route',
                layout: {
                    'line-join': 'round',
                    'line-cap': 'round'
                },
                paint: {
                    'line-color': [
                        'match',
                        ['get', 'travelType'],
                        'TRANSIT', 'red',
                        'WALK', 'green',
                        'gray'
                    ],
                    'line-width': 4
                },
                filter: ['==', ['geometry-type'], 'LineString']
            })
        
            getRoute()
        })
    </script>
</body>
</html>
content_copy
Copied to clipboard