简体   繁体   中英

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

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. map.getLayerGroup(yearcmpGrp).addLayer(samplevectorlyr) is not working

This worked

yearcmpGrp.getLayers().push(samplevectorlyr);

Thanks @Mike. I am posting as an answer bcz it might help somebody.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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