1

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.

nerdess
  • 10,051
  • 10
  • 45
  • 55
  • 1
    `getLayers()` returns a `collection` which has an `add` event. so try `map.getlayers().on('add', function(){ });` – Mike Dec 12 '22 at 09:12

1 Answers1

1

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.

Mads Akselsen
  • 249
  • 1
  • 5