Mapbox-GL Routing Service
Show routing service results on a Mapbox-GL map
<!DOCTYPE html>
<html>
<head>
    <!--  Include mapboxgl javascript and css -->
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.0/mapbox-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 {
            margin: 0;
            width: 100%;
            height: 100%;
        }
        #map {
            width: 100%;
            height: 100%;
        }
        #message {
            display: none;
            position: absolute;
            top: 0;
            background-color: #FF8319;
            color: white;
            z-index: 400;
            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' };
        
        const attributionText = `__targomo_attribution__`;
        
        // add the map and set the initial center to berlin
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'https://api.maptiler.com/maps/positron/style.json?key=__your_maptiler_api_key__',
            zoom: 13,
            center: target,
            attributionControl: false
        })
            .addControl(new mapboxgl.NavigationControl())
            .addControl(new mapboxgl.AttributionControl({ compact: true, customAttribution: attributionText }));
        
        // 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 mapboxgl.Marker({ draggable: true })
            .setLngLat(source).addTo(map);
        const targetMarker = new mapboxgl.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
            });
            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