[GIS] How to use Leaflet’s overlayadd event

leaflet

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?

Best Answer

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/

Related Question