Вопрос

I'm trying to toggle the visibility of a layer in a Leaflet/Mapbox map with this function:

var showOne = document.getElementById("one");

showOne.onclick = function(e) {
    if (this.className='active') {
        map.removeLayer(groupOne);
        this.className = '';
    } else {
        map.addLayer(groupOne);
        this.className = 'active';
    }
};

That toggles one layer off but not back on. How can I toggle the layer back to visible? Then, how can I toggle multiple layers -- will this work:

var showOne = document.getElementById("one");

showOne.onclick = function(e) {
    if (this.className='active') {
        map.removeLayer(groupOne);
        map.removeLayer(groupTwo);
        this.className = '';
    } else ...

fiddle

Это было полезно?

Решение

Not sure if this is the only problem, but:

if (this.className='active') { // Assigns 'active' to className (always true)

Should be:

if (this.className=='active') { // Compares className with 'active'

Edit: Seems to do the trick: http://jsfiddle.net/Q3hfP/1/

Другие советы

OK I found other documentation that suggests the answer is to form a layerGroup:

var layersAll = L.layerGroup([groupOne, groupTwo]);

...

map.removeLayer(layersAll);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top