26

See the Leaflet tutorial for adding a layer control to your map:

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

How do I use the removeLayer function to remove the "GrayScale" map from the control using a map.on('click') event?

The code would be:

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

2 Answers 2

33

If you want to remove the grayscale map from the start just delete:

    "Grayscale": grayscale,

From

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

If you want to remove the layer on a click you call it as a method on the map object. Like so:

map.removeLayer(grayscale)

To remove it from the control you first have to assign the control to a variable. Change this:

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

To this:

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

Then you can call:

lcontrol.removeLayer(grayscale) 

..to remove it from the control.

0
1

When you add a layer to L.control, you add an object by reference. Instead of remove the layer, you can modify the object :

let baseMaps = {
    "Grayscale": grayscale,
    "Streets": streets
};
L.control.layers(baseMaps, overlayMaps).addTo(map);
baseMaps = {
    "Streets": streets
};

I did this with overlayMaps. Each time I uploaded new markers, the old ones still stayed in overlay. And I realized I made an array from markers and pushed new ones in it. So I reset my array before upload : overlayMarkers.length = 0 and it works !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.