2

In the example at http://jsfiddle.net/gwulo/w6cvagoL/4/ I'd like to force only one overlay to be visible. So if you select Cities2 in the layer switcher, the Cities1 overlay should be de-selected.

I'm trying to use the overlayadd event:

    map.on('overlayadd', function(eo) {
    if (eo.name === 'Cities1') {
        this.removeLayer(cities2);
    } else {
        this.removeLayer(cities1);
    }
    });

When I click the Cities2 layer in the layer switcher, I'd expect the above function to be run once, with the parameter set to Cities2. In fact the function is called five times, with the parameter alternating between layers: Cities2 / 1 / 2 / 1 / 2

What causes the event to be triggered so often, and how can I identify which is the event I'm interested in and which I should ignore?

1 Answer 1

1

Though I don't know why the event is being fired so often, the problem seems to be fixed by adding a short delay with setTimeout and using map.removeLayer (as this.removeLayer will not work within the timeout function), like this:

map.on('overlayadd', function(eo) {
    if (eo.name === 'Cities1'){
        setTimeout(function(){map.removeLayer(cities2)}, 10);
    } else {
        setTimeout(function(){map.removeLayer(cities1)}, 10);
    }
    });

Example fiddle:

http://jsfiddle.net/nathansnider/s408tnwv/

1

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.