2

I have a Leaflet map with a control to switch between various basemaps or toggle on/off some overlay data.

  //Basemaps are all a-okay
  //Start with no polylines in my overlayData
  items = [];
  flightpaths = L.layerGroup(items);

  overlayData = {
  "Videos": flightpaths
  };

  L.control.layers(baseMaps, overlayData, {position:"bottomright"}).addTo(map);

But my overlayMaps objects are coming in at random times. I'm using Leaflet.Draw to allow people to create polylines, so each time there is a draw:created a new object gets created that I want the controller to be aware of. There is some other analysis I do in here but the basic flow is-

map.on('draw:created', function (e) {
  item = e.layer;
  items.push(item);
  flightpaths = L.layerGroup(items);

  overlayData = {
      "Videos": flightpaths
  };

  L.control.layers(baseMaps, overlayData, {position:"bottomright"}).addTo(map);
});

But this (unsurprisingly) add just a second control to my map. How do I get the original control to recognize that overlayData has been changed?

2

So looks like one solution is just to remove the controller and and recreate it. So when I initialize it outside of my Leaflet.draw event handler, declare it as a variable.

  controller = L.control.layers(baseMaps, overlayData, {position:"bottomright"}).addTo(map);

and then within my function

  controller.removeFrom(map);
//Add the new data to overlayData, then
  controller = L.control.layers(baseMaps, overlayData, {position:"bottomright"}).addTo(map);
1

Little update : leaflet documentation is not updated, but removeFrom() function does not exist anymore (see this post). You have to use :

controller.remove();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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