Search code examples
openlayers-6openlayers-5

Openlayers 5 - Dynamically changing interactions


Is there a way to dynamically change interactions in Openlayers? I set interactions

import {defaults as defaultInteractions} from 'ol/interaction.js';

var interactions = defaultInteractions({
       constrainResolution: true, 
       onFocusOnly: true, 
       doubleClickZoom: false, 
       altShiftDragRotate:false, 
       pinchRotate:false
    });

But let's say I want to have a user button where they can turn on (or toggle between) pinchRotate? I've tried searching this questions a thousand different ways and can't seem to find how to modify the interactions after the map is rendered.


Solution

  • The interactions would need to be assigned to variable names and added to the default collection instead of being included in the defaults. Set them inactive if your don't need them immediately. Your button can then toggle the interaction active settings.

    var dragRotate = new DragRotate();
    var pinchRotate = new PinchRotate();
    
    var interactions = defaultInteractions({
           constrainResolution: true, 
           onFocusOnly: true, 
           doubleClickZoom: false, 
           altShiftDragRotate:false, 
           pinchRotate:false
        }).extend([dragRotate, pinchRotate]);
    
    dragRotate.setActive(false);
    pinchRotate.setActive(false);
    
    myRotateButton.addEventListener('click', function() {
        // turn rotation on/off
        dragRotate.setActive(!dragRotate.getActive());
        pinchRotate.setActive(!pinchRotate.getActive());
    }, false);