openlayersopenlayers-6

Openlayers: Is there a map event that fires when a new layer has been added?


I am searching for a event that fires when a new layer has been added to an openlayers map.

Sth like map.on('layeradded')...

I found all of these events: https://gis.stackexchange.com/questions/252946/what-are-the-possible-listeners-and-event-types-for-an-openlayers-map-ol-map and searched in the docs but could not find anything suitable.


Solution

  • You can use a class to extend EventTarget, so whenever you add a layer, you also dispatch your own event.

    const myClass extends EventTarget {
    
      addLayer(layer) {
        this.map.addLayer(layer);
        this.dispatchEvent(new CustomEvent(`layer-added`, detail: {layer}));
      }
    }

    You can add data of your choosing in the dispatched event, so the eventListener, for example, knows which layer has been added - or whatever the use case is.