传单:如何使用removeLayer?


15

这让我发疯。请参见《 Leaflet》教程,以向地图添加图层控件:

L.Icon.Default.imagePath = "Scripts/images";

var mapUrl = 'http://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png';
var secondMap = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';

var littleton = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'),
denver = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'),
aurora = L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.'),
golden = L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.');

var cities = L.layerGroup([littleton, denver, aurora, golden]);

var grayscale = L.tileLayer(mapUrl, { id: mapUrl }),
streets = L.tileLayer(secondMap, { id: secondMap });

var map = L.map('map', {
    center: [39.73, -104.99],
    zoom: 10,
    layers: [grayscale, cities]
});

var baseMaps = {
    "Grayscale": grayscale,
    "Streets": streets
};

var overlayMaps = {
    "Cities": cities
};

L.control.layers(baseMaps, overlayMaps).addTo(map);

现在,如何使用removeLayer函数通过map.on('click')事件从控件中删除“ GrayScale”地图?该代码将是:

map.on('click', function(){
    //remove GrayScale
});

您是否希望用户能够通过按钮删除灰度?还是要由于其他事件而将其动态删除?还是只希望地图开始时根本没有灰度层?
hexamon 2014年

让我们说说最简单的解决方案:动态地影响事件。例如,map.on('click',function(){})。我将相应地编辑我的帖子。
yesman 2014年

Answers:


21

如果要从一开始就删除灰度图,只需删除:

    "Grayscale": grayscale,

var baseMaps = {
    "Grayscale": grayscale,
    "Streets": streets
};

如果要单击删除图层,则可以将其作为地图对象上的方法调用。像这样:

map.removeLayer(grayscale)

要从控件中删除它,您首先必须将控件分配给变量。更改此:

L.control.layers(baseMaps, overlayMaps).addTo(map);

对此:

lcontrol = L.control.layers(baseMaps, overlayMaps).addTo(map);

然后,您可以致电:

lcontrol.removeLayer(grayscale) 

..将其从控件中删除。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.