在Leaflet中动态地向图层控件中添加图层组中的图层

11

我正在通过xhr调用创建一组向量图层,并希望将它们添加到一个图层组中,然后将该图层组添加到一个图层控件中。我的思路是这样的:

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.

好的,我尝试了上述方法(没有使用图层组部分),它有效(代码如下)。

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

然后

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

然而,我无法弄清如何使用图层组来完成它。欢迎提供建议。

1个回答

15

在您的ajax回调函数中,您应该查找

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

点击此处查看示例:http://jsfiddle.net/FranceImage/9xjt8223/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接