简体   繁体   中英

Mapbox draw direction via two markers

How can i draw route direction from start to finish if I have coordinates of this two points? Now my code looks like this and it just gave me 2 static markers on map

var map = L.mapbox.map('map', 'mapbox.streets', {
    zoomControl: false
}).setView([start.lat, start.lng], 12);
map.attributionControl.setPosition('bottomleft');
var directions = L.mapbox.directions({
    profile: 'mapbox.walking'
});
var directionsLayer = L.mapbox.directions.layer(directions).addTo(map);
L.marker([start.lat, start.lng], {}).addTo(map);
L.marker([finish.lat, finish.lng], {}).addTo(map);

If I understand correctly, you wish to use Mapbox's direction and routing layer to get the walking route between the two points and display it. To do so you need to set the origin and destination points and call the query() function of direction . You also need to add a routes control to the map. The revised code is as follows.

// example origin and destination
var start = {lat: 22.3077423, lng: 114.2287582}; 
var finish = {lat: 22.3131334, lng: 114.2205973};

var map = L.mapbox.map('map', 'mapbox.streets', {
    zoomControl: false }).setView([start.lat, start.lng], 14); 

map.attributionControl.setPosition('bottomleft'); 
var directions = L.mapbox.directions({
    profile: 'mapbox.walking' 
});

// Set the origin and destination for the direction and call the routing service
directions.setOrigin(L.latLng(start.lat, start.lng)); 
directions.setDestination(L.latLng(finish.lat, finish.lng));   
directions.query(); 

var directionsLayer = L.mapbox.directions.layer(directions).addTo(map); 
var directionsRoutesControl = L.mapbox.directions.routesControl('routes', directions)
    .addTo(map);

You may not need to add the origin / destination markers yourself, as origin / destination markers would be displayed as part of the directions control.

You'll need a polyline for that. Leaflet's (Mapbox is an extended version of Leaflet) class L.Polyline is what you need:

Reference: http://leafletjs.com/reference.html#polyline

Code:

var polyline = new L.Polyline([
    [start.lat, start.lng],
    [finish.lat, finish.lng]
]).addTo(map);

Example on Plunker: http://plnkr.co/edit/2XSeS1?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM