angularopenlayersopenlayers-6

OpenLayers - LayerSwitcher change visibility


I am working on an Angular based application which is using OpenLayers to show given data on a map.

For this map I am using a LayerSwitcher (ol-ext.control.LayerSwitcher):

const layerSwitcher = new LayerSwitcher({
        tipLabel: 'Layers',
        trash: false,
        width: 800
    });
this.map.addControl(layerSwitcher);

I have also a LayerGroup, to which I am dynamically adding vector layers. All of these layers can be selected / deselected via the LayerSwitcher one by one or by ticking the checkbox of the whole LayerGroup as well.

I wish to have the functionality that when one vector layer is click to select / deselect in the LAyerSwitcher (with the red circle marked tick), then I want to do some operation on my map object. I have added a listener for change events of visibility:

const vectorLayer = this.myFunctionToGetTheLayer(input1, input2);
vectorLayer.on('change:visible', function () {
    console.log('selected')
});
this.layerGroup.getLayers().push(vectorLayer);

enter image description here

This works well, when I click the checkbox in the LayerSwitcher, then the log disappears on the console.

But instead of the log, I want to have something like this:

...this.map.getLayers()...

But the this.map is undefined within this function.

Is there any way to operate on the whole map while listening to a change event of a layer?


Solution

  • function has it's own context, so there is no map property. Try using arrow function which has context of it's parent

    vectorLayer.on('change:visible', () => {
       console.log('selected')
       ... this.map ... etc
    });