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......


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....

1 Answer 1


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...

  • Great thanks for help.... i already read the docmentation and solved my problem, although correct answer, +1 for effort Commented Sep 8, 2015 at 8:19

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.