我按照这个很棒的教程添加,因为它能够将它添加到我的路由机器;但是,我想将航点保存在本地存储中并在需要时加载它们。
我在创建路由机时尝试了这个:
if (map && !this.control) {
this.control = L.Routing.control({
collapsible: true,
show: false,
position: 'bottomleft',
lineOptions: {
styles: [{ color: 'chartreuse', opacity: 1, weight: 5 }]
},
waypoints: [null], //<--- I set the waypoints to null
createMarker: function(i, wp, nWps) {
if (i === 0) {
return L.marker(wp.latLng, {
icon: startIcon,
draggable: true
});
}
if (i === nWps - 1) {
return L.marker(wp.latLng, {
icon: endIcon,
draggable: true
});
}
}
})
.on('routingstart', this.handleLoader.bind(this))
.on('routeselected', function(e) {
var route = e.route;
})
.on('routesfound routingerror', this.handleLoader.bind(this));
然后在开始和目标事件的点击事件的初始侦听器中:
map.on(
'click',
function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
function createMarkerHelper(marker) {
setUserMarkers(marker);
}
L.popup()
.setContent(container)
.setLatLng(e.latlng)
.openOn(map);
L.DomEvent.on(
startBtn,
'click',
function() {
var wayPointStart = this.control.getWaypoints()[0].latLng;
if (wayPointStart != null && userMarkers[0] !== undefined) {
this.control.spliceWaypoints(0, 1, userMarkers[0]);
} else {
this.control.spliceWaypoints(0, 1, e.latlng);
createMarkerHelper(e.latlng);
}
map.closePopup();
}.bind(this)
);
L.DomEvent.on(
destBtn,
'click',
function() {
var wapPointDestination = this.control.getWaypoints()[1].latLng;
if (wapPointDestination != null && userMarkers[1] !== undefined) {
this.control.spliceWaypoints(
this.control.getWaypoints().length - 1,
1,
userMarkers[1]
);
} else {
this.control.spliceWaypoints(
this.control.getWaypoints().length - 1,
1,
e.latlng
);
createMarkerHelper(e.latlng);
}
map.closePopup();
}.bind(this)
);
}.bind(this)
);
所以这就是我在一个开始click
事件时尝试的:
function() {
var wayPointStart = this.control.getWaypoints()[0].latLng;
if (wayPointStart != null && userMarkers[0] !== undefined) {
this.control.spliceWaypoints(0, 1, userMarkers[0]);
} else {
this.control.spliceWaypoints(0, 1, e.latlng);
createMarkerHelper(e.latlng);
}
map.closePopup();
}.bind(this)
所以基本上我正在使用该getWaypoints
方法来检查航路点是否为空,(它将在重新开始期间)并检查是否有任何标记在本地存储中,如果该条件为真,它自然会加载标记。如果不是真的,它只会像平常一样设置它。
然后后来 Leaflet 有一个更新功能,你可以用它来查看 props 是否发生变化:
updateLeafletElement(fromProps, toProps) {
var start =
toProps.userMarkers[0] !== undefined &&
this.control.getWaypoints()[1].latLng != null
? toProps.userMarkers[0]
: null,
destination =
toProps.userMarkers[1] !== undefined &&
this.control.getWaypoints()[1].latLng != null
? toProps.userMarkers[1]
: null;
this.control.spliceWaypoints(0, 1, start);
this.control.spliceWaypoints(this.control.getWaypoints().length - 1, 1, destination);
if (toProps.removeRoutingMachine !== false) {
this.control.setWaypoints([]);
}
}
我的想法是,这将始终确保标记始终被更新。但它没有奏效。
有任何想法吗?提前致谢!