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

时间:2020-10-15 09:45:23

标签: javascript openlayers openlayers-6

我想在单击按钮时将图层动态添加到图层组。 我添加了一个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 !!
    } 

我想在for循环中将多个图层添加到layergroup。 map.getLayerGroup(yearcmpGrp).addLayer(samplevectorlyr)无法正常工作

1 个答案:

答案 0 :(得分:1)

这有效

yearcmpGrp.getLayers().push(samplevectorlyr);

感谢@Mike。我发布的答案是bcz,可能对某人有帮助。

相关问题