0

In leaflet I'm trying to get a function going that when a user clicks on a certain (image)layer in the layer control panel and it sees that a conflicting layer is on, it turns the conflicting layer off and also turns it off in the layer control panel,

map.on('overlayadd', function(e) {
  switch(e.layer){
    case s2: if(map.hasLayer(s3)){map.removeLayer(s3);}
      break;
    case s3: if(map.hasLayer(s2)){map.removeLayer(s2);}
      break;
      default: break;
}

var overlays = {

"A": s1,
"B": s5,
"C": s6,
"D": s2,
"E": s3,
"F": s4,
"G": s7,
};

L.control.layers(baseLayers,overlays,{collapsed:false}).addTo(map);
0

1 Answer 1

0

L.control.layers does not like being changed inside overlayadd event processing function. Simple trick is to put layer manipulation actions inside setTimeout processing function with just a slight delay. Then layer will be removed from map and unchecked in layer control.

In your case this would look like:

function removeConflictingLayer(layer) {
  switch(layer) {
    case s2: if (map.hasLayer(s3)) {map.removeLayer(s3);}
      break;
    case s3: if (map.hasLayer(s2)) {map.removeLayer(s2);}
      break;
    default: break;
  }
}

map.on('overlayadd', function(e) {
  setTimeout(removeConflictingLayer, 10, e.layer);
}

1
  • That worked perfectly thanks very much!
    – GladH
    Apr 8, 2020 at 15:07

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.