OpenLayers – How to Detect Zoom Change

openlayerszoom

There is no appropriate zoom event listener in OpenLayers v5.3 yet, but there is a workaround suggested in this ticket:

You can use this.view.instance.on('change:zoom', evt => console.log(this.view.zoom)); where view is a viewChild : @ViewChild(ViewComponent) view: ViewComponent; to detect zoom changes.

Can anyone please explain to newbies how to utilize this? How to use that code with an instance of a map view which is usually got by calling map.getView()?

Best Answer

To hook on zoom end event is fairly simple: listen to moveend event and compare old and new zoom:

var currZoom = map.getView().getZoom();
map.on('moveend', function(e) {
  var newZoom = map.getView().getZoom();
  if (currZoom != newZoom) {
    console.log('zoom end, new zoom: ' + newZoom);
    currZoom = newZoom;
  }
});

If you want to catch zoom start, it's more complicated. I found a way but I don't like it, it's not how it should be done. I noticed that exposed method view.animate is called before any animated map event. I replaced it with my own, where I check for zoom, and then call original method:

view.origAnimate = view.animate;

view.animate = function(animateSpecs) {
  if (typeof animateSpecs.resolution !== 'undefined') {
    var currZoom = this.getZoom();
    var newZoom = this.getZoomForResolution(animateSpecs.resolution);
    if (newZoom != currZoom)) {
      console.log('zoom start, new zoom: ' + newZoom);
    }
  }
  this.origAnimate(animateSpecs);
};
Related Question