How to limit MouseWheelZoom to only apply while sh

2019-08-23 22:38发布

问题:

I want mouseWheelZoom to only zoom the map while the shift key is pressed. But ol.interaction.MouseWheelZoom options does not include a condition. There is a handleEvent() method however.

I can see that ol.events.condition.shiftKeyOnly(mapBrowserEvent) returns true if only the shift-key is pressed.

So how can I override the handleEvent() method?

using typescript:

export class ShiftMouseWheelInteraction extends  ol.interaction.MouseWheelZoom {

   public handleEvent = function(evt){
        if (ol.events.condition.shiftKeyOnly(evt) === true) {
            return  ol.interaction.MouseWheelZoom.handleEvent(evt);
        }
        else {
            return false;
        }
    }
}

Then I add add this interaction to the map and enable MouseWheelZoom as a default interaction.

  this.map = new ol.Map({
        layers: layers,
        interactions: ol.interaction.defaults({
          mouseWheelZoom: true
        })
    });
  this.map.addInteraction(shiftMouseWheelInteraction);

But it is not zooming the map?

ol.interaction.MouseWheelZoom extends ol.interaction

The base interaction constructor has a handleEvent option but the subclass does not allow passing this parameter to the base interaction.

ol.interaction.MouseWheelZoom = function(opt_options) {

  ol.interaction.Interaction.call(this, {
    handleEvent: ol.interaction.MouseWheelZoom.handleEvent
  });

回答1:

I solved this using an event listener that prevents the default behaviour.

map.on('wheel', function(evt) {
    wheelZoomHandler(evt);
});
wheelZoomHandler(evt) {
      if (ol.events.condition.shiftKeyOnly(evt) !== true) {
          evt.browserEvent.preventDefault();
      }
  }