2
votes

I'm using Mapbox to integrate in a javascript/php project. So far so good. Works great. Looking around their api I was wondering whether it was possible to have a mix between mapbox-gl-directions and mapbox-directions api. They don't seem to be the same thing.I really like the example from mapbox-gl-directions which gives the user options to select between driving, cycling and walking. But I already have coordinates for the origin point and coordinates for the destination point. I don't necessarily need the user to input those coordinates but I would also like to leave the user the option to enter alternative coordinates if he wanted to. How can I add starting and destination points to the mapbox-gl-directions just like the mapbox-directions-api? I've looked everywhere in their docs.

mapbox-gl-directions :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Display driving directions</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.6.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.6.1/mapbox-gl.css" rel="stylesheet" />
<style>
    body { margin: 0; padding: 0; }
    #map { position: absolute; top: 0; bottom: 0; width: 100%; };
</style>
</head>
<body>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.0.2/mapbox-gl-directions.js"></script>
<link
    rel="stylesheet"
    href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.0.2/mapbox-gl-directions.css"
    type="text/css"
/>
<div id="map"></div>

<script>
    mapboxgl.accessToken = 'pk.eyJ1Ijoid2ViYjI0aCIsImEiOiJjazU3a2lkbW4wNGJrM2RvNnNrNnBzbGlxIn0.GGnF34IsMQyqKNoam241tA';
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [-79.4512, 43.6568],
        zoom: 13
    });

    map.addControl(
        new MapboxDirections({
            accessToken: mapboxgl.accessToken
        }),
        'top-left'
    );
</script>

</body>
</html>
1

1 Answers

2
votes

Turn

map.addControl(
    new MapboxDirections({
        accessToken: mapboxgl.accessToken
    }),
    'top-left'
);

into

var directions = new MapboxDirections({
        accessToken: mapboxgl.accessToken
    });

map.addControl(directions,'top-left');

map.on('load',  function() {
    directions.setOrigin([12, 23]); // can be address in form setOrigin("12, Elm Street, NY")
    directions.setDestinaion([11, 22]); // can be address
})