Mapbox 通过两个标记绘制方向

Mapbox draw direction via two markers

如果我有这两点的坐标,如何绘制从头到尾的路线方向? 现在我的代码看起来像这样,它只在地图

上给了我 2 个静态标记
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);

为此你需要一条折线。 Leaflet的(Mapbox是Leaflet的扩展版)classL.Polyline就是你需要的:

参考:http://leafletjs.com/reference.html#polyline

代码:

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

Plunker 示例:http://plnkr.co/edit/2XSeS1?p=preview

如果我没理解错的话,你希望利用Mapbox的方向路由层获取两点之间的步行路线并显示出来。为此,您需要设置起点和终点并调用 directionquery() 函数。您还需要向地图添加路线控件。修改后的代码如下

// 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);

您可能不需要自己添加起点/终点标记,因为起点/终点标记会作为方向控件的一部分显示。