Search code examples
javascripteventsopenlayersopenlayers-5

How do I subscribe to OpenLayers 5.3.0 events in JavaScript?


I see that OpenLayers 5.3.0 is making use of observables. The docs also cover events.

How would I alter this starting example to .subscribe() to events in general? I'm struggling bridging the gap between docs and use.

import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';

new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: new XYZ({
        url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

I've seen examples with older versions of OpenLayers that may not apply here. At least in the linked example above, "eventListeners" is not listed as a property on 5.3.0 and seems old and callback-related (not observable).

I did see a more recent, similar question here with helpful resources listed. I could use a script example to help get started.


Solution

  • You can register events, for example on the map. In the latest examples there is an example for the moveend event.

    var map = new Map({
        layers: [
            new TileLayer({
                source: new OSM()
            })
        ],
        target: 'map',
        view: new View({
            center: [0, 0],
            zoom: 2
        })
    });
    
    map.on('moveend', function(evt){console.log(evt);});