[GIS] How to add layers and update layer control dynamically : leaflet

esri-leafletgoogle mapsleafletleaflet-draw

Introduction

I am working with the leaflet api, where the user can draw shapes to a
map(image)…

Initially the layer control(handling 1 layer) is added for base map
using imageoverlay……

Problem

Now, I have added a button of id newLyer to page where click event
handles the creation of new layer…..i.e user can create new layer
and update layer control(which is now handling 2 layers)….

I have used several methods to create the layers and adding to control
but failed….

Adding new layer to layerGroup

var layerGroup = new L.LayerGroup(),
                    imageOverlayUrl = 'aa.jpg',
                    // New imageoverlay added to the layergroup
                    imageOverlay = new L.ImageOverlay(imageOverlayUrl, bounds).addTo(layerGroup),
                    // New featuregroup added to the layergroup
                    featureGroup = new L.FeatureGroup().addTo(layerGroup);

LayerControl where i needed to add the control(if i am correct)

        var layerControl = new L.control.layers({
            'Main': layerGroup,
            //here i need to add new layer control
            }, null, { collapsed: false }).addTo(map);

OnClick function with so far static code, this will be executed on click

        $('#newLayer').click(function addNewLayer() {
            // Second layergroup not added to the map yet
            var layerGroupNew = new L.LayerGroup(),
                imageOverlayUrlNew = 'bb.png',
                // New imageoverlay added to the second layergroup
                imageOverlayNew = new L.imageOverlay(imageOverlayUrlNew, bounds).addTo(layerGroup2),
                // New featuregroup added to the second layergroup
                featureGroupNew = new L.FeatureGroup().addTo(layerGroupNew);
        });

In Short

Initially, i have one layer with its control, now onclick function
creates the new layer which will be added to the map but how i can add
this layer into layerControl….

Best Answer

There are public methods in L.Control.Layers control to add base layers and overlays dinamically (see full reference):

  • addBaseLayer(layer, name) to add new base layer
  • addOverlay(layer, name) to add new overlay

So, when user clicks on a button, you create new layer and just add it to a control:

$('#newLayer').click(function addNewLayer() {
    //create new layer
    var imageOverlayNew = new L.imageOverlay(imageOverlayUrlNew, bounds);
    //add it to a control
    layerControl.addOverlay(imageOverlayNew, newLayerName);
});

And looks like you don't need to use L.LayerGroup here...