如何使用Leaflet Routing Machine完全删除先前绘制的路线?要么
docs here没有解释这是怎么做的,要么我以某种方式设法错过它.
阅读conversation here我目前正在做以下几点
if (routing)
{
routing.spliceWayPoints(0,2);
removeControl(routing);
routing = null;
}
虽然这是有效的,但我不清楚它实际上是合法的做事方式,它不会导致内存泄漏.我希望这里有人有明确的解决方案.
最佳答案 根据Leaflet API文档,要删除控件,我们可以调用基类L.Control
http://leafletjs.com/reference-1.2.0.html#control中可用的方法“remove”
另一种选择是使用L.map类http://leafletjs.com/reference-1.2.0.html中提供的“removeControl”方法
为了说明这一点,我准备了一个小帮助脚本来以更面向对象的方式管理地图.您可以调用addRoutingControl和removeRoutingControl来添加并从地图中完全删除控件.
在这个例子中,我使用了Leaflet map对象中的“removeControl”方法.
MapHelper = (function ($) {
'use strict';
var settings = {
center: [0, 0],
zoom: null,
};
var mapId = '';
var map = null;
var baseMaps = {};
var overlayMaps = {};
var routingControl = null;
var init = function (mapLayerId, options) {
settings = $.extend(settings, options);
mapId = mapLayerId;
initMap();
};
var getMap = function () {
return map;
};
var addRoutingControl = function (waypoints) {
if (routingControl != null)
removeRoutingControl();
routingControl = L.Routing.control({
waypoints: waypoints
}).addTo(map);
};
var removeRoutingControl = function () {
if (routingControl != null) {
map.removeControl(routingControl);
routingControl = null;
}
};
var panMap = function (lat, lng) {
map.panTo(new L.LatLng(lat, lng));
}
var centerMap = function (e) {
panMap(e.latlng.lat, e.latlng.lng);
}
var zoomIn = function (e) {
map.zoomIn();
}
var zoomOut = function (e) {
map.zoomOut();
}
var initMap = function () {
var $this = this;
map = L.map(mapId, {
center: settings.center,
zoom: settings.zoom,
crs: L.CRS.EPSG3857,
attributionControl: true,
contextmenu: true,
contextmenuWidth: 140
});
baseMaps["OSM"] = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}).addTo(map);
};
var invalidateMapSize = function () {
map.invalidateSize();
}
return {
init: init, addRoutingControl: addRoutingControl, removeRoutingControl: removeRoutingControl,
panMap: panMap, invalidateMapSize: invalidateMapSize, getMap: getMap
}
}(jQuery));
然后你可以在你的页面中使用它,如下所示:
<button id="addRoute">Add Route</button>
<button id="remoteRoute">Remove Route</button>
<div id="map" style="width: 400px; height: 400px;"></div>
<script>
MapHelper.init('map', {
zoom: 10,
center: L.latLng(51.509865, -0.118092),
});
$('#addRoute').on('click', function() {
MapHelper.addRoutingControl( [
L.latLng(50.509865, -1.118092),
L.latLng(51.509865, -0.118092)
]);
});
$('#remoteRoute').on('click', function() {
MapHelper.removeRoutingControl();
});
</script>
可以在这里测试:https://codepen.io/anon/pen/GMXWMm
我们可以期待Leaflet正确地管理它,事实上,如果您使用浏览器调试页面,您可以看到控件已从DOM树中完全删除.