Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding layers in layer group dynamically to layer control in leaflet

Tags:

leaflet

I am creating a bunch of vector layers via xhr calls, and want to add the to a layer group and add that layer group to a layer control. The way I am thinking is

1. Add a layer control to the map with only the base layer in the control
2. Create a layer via `xhr`  
   2.1. Check if layer group LG exists in layer control  
      2.1.1. If yes, add layer to LG
      2.1.2. If no, add layer group LG to layer control and add layer to LG
3. Repeat #2 above.

Well, I tried the above (without the layer group part) and that works (code below).

LC = L.control.layers({'OSM': osm}).addTo(map);

and then

x.onload = function(e) {
    if (x.readyState === 4) {
        if (x.status === 200) {
            var res = JSON.parse(x.responseText);
            ..
            LC.addOverlay(lyr, "layer name");
        }
    }
};

However, I can't figure out to do it with a layer group. Suggestions welcome.

like image 844
punkish Avatar asked Aug 18 '14 21:08

punkish


1 Answers

In your ajax callback, you should find

layerGroup = L.layerGroup()
        .addLayer(vector1))
        .addLayer(vector2))
        .addLayer(vector3))
        ....
        .addTo(map);

if(layerControl === false) {  // var layerControl set to false in init phase; 
    layerControl = L.control.layers().addTo(map);
}

layerControl.addOverlay(layerGroup , "My batch of vectors");

see example here: http://jsfiddle.net/FranceImage/9xjt8223/

like image 102
YaFred Avatar answered Oct 01 '22 00:10

YaFred