简体   繁体   English

如何在ol6中将多个矢量图层动态添加到图层组?

[英]How to dynamically add multiple vector layers to a layer group in ol6?

I want to add layers to a layergroup dynamically on a button click.我想通过单击按钮动态地将图层添加到图层组。 I have added an OSM layer我添加了一个 OSM 层

var map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      title: 'OSM',
      source: new OSM(),
      opacity: 0.5,
    })
  ]
  });
  
  
  //--On button click--
  var yearcmpGrp = new LayerGroup({
      title: 'Year Comparison',
      layers: []
  });
  map.addLayer(yearcmpGrp); //this add a new layergroup
    
    for(var i=fromyr;i<=toyear;i++){
       var sampledata = data;
       var samplevectorlyr = new VectorLayer({
          title:i,
          source: new VectorSource({
            features: new GeoJSON().readFeatures(sampledata, {
                dataProjection: 'EPSG:32643',
                featureProjection: 'EPSG:32643',
            }),
          }),
          style: new Style({
            image: new Circle({
                radius: 7,
                fill: new Fill({color: colorpick[i]}),
                stroke: new Stroke({
                  color: [255,0,0], width: 2
                })
              })
          }),
          opacity: 0.5,
        });
         //map.addLayer(samplevectorlyr); //this works fine & add a new layer outside layer group
         map.getLayerGroup(yearcmpGrp).addLayer(samplevectorlyr); //This don't work !!
    } 

I want to add multiple layers to layergroup in the for loop.我想在 for 循环中向 layergroup 添加多个图层。 map.getLayerGroup(yearcmpGrp).addLayer(samplevectorlyr) is not working map.getLayerGroup(yearcmpGrp).addLayer(samplevectorlyr)不起作用

This worked这有效

yearcmpGrp.getLayers().push(samplevectorlyr);

Thanks @Mike.谢谢@迈克。 I am posting as an answer bcz it might help somebody.我发布作为答案 bcz 它可能会帮助某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM