[GIS] How to update data in Leaflet Control

javascriptleafletleaflet-draw

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?

Best Answer

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);