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.