Display navigation directions
Use the mapbox-gl-directions plugin to show results from the Mapbox Directions API. See the example: https://docs.mapbox.com//mapbox-gl-js/example/mapbox-gl-directions/
by Boyanliuu
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.css">
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.css">
<div id="map"></div>
CSS
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
JavaScript
mapboxgl.accessToken = 'pk.eyJ1Ijoic3ByaW5nZ2VtIiwiYSI6ImNrc2c3YTJ0YzFkbjMycm5xaGR0MnludWEifQ.k04fviSsj-CTCWSboCHZ8Q';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-79.4512, 43.6568],
zoom: 13
});
const directions = new MapboxDirections({
accessToken: mapboxgl.accessToken,
unit: "metric",
profile: "mapbox/driving",
alternatives: false,
geometries: "geojson",
controls: { instructions: false },
flyTo: false,
});
map.addControl(
directions,
'top-left'
);
directions.on("route", (data) => {
console.log(data);
})