[GIS] Selecting layer by default using Leaflet

leafletleaflet-draw

I am working with the leaflet, where we first load the imageoberlay to the map using user input.

Now, i been trying different methods to select that layer by default.

The problem is only that the first layer not loaded on map until i click on the radio button.

How can i select layer by default. I am doing something like :

Script

        // New layergroup, note it's not added to the map yet
        var layerGroup = new L.LayerGroup(),
            imageOverlayUrl = firstImage,
            // 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);

        //dynamic method for adding new layer
        var layerGroupings = { "Main": layerGroup };
        var layerControl = new L.control.layers(layerGroupings, null, { collapsed: false });
        layerControl.addTo(map);

When new layer loaded, it should be selected by default.

How can i do that?

Best Answer

Just add the Layergroup to your map with the addTo-method.

layerGroup.addTo(map);

In your code-example this could be done here:

// New layergroup, note it's not added to the map yet
        var layerGroup = new L.LayerGroup(),
            imageOverlayUrl = firstImage,
            // 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);


     layerGroup.addTo(map);

        //dynamic method for adding new layer
        var layerGroupings = { "Main": layerGroup };
        var layerControl = new L.control.layers(layerGroupings, null, { collapsed: false });
        layerControl.addTo(map);