Search code examples
javascriptopenlayers

Openlayers - Enable interaction after map initialization


I'm using openlayers 6.5.

Here is how I start:

/*** Set the map ***/
map = new ol.Map({
    target: map_element,
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([
            '24.6859225',
            '45.9852129',
        ]),
        zoom: 6,
    }),
    interactions: ol.interaction.defaults({
        'DragPan': false,
        'Keyboard': false,
        'PinchZoom': false,
        'ZoomDelta': false,
        'PinchRotate': false,
        'OnFocusOnly': false,
        'ZoomDuration': false,
        'ShiftDragZoom': false,
        'MouseWheelZoom': false,
        'DoubleClickZoom': false,
        'AltShiftDragRotate': false
    }),
    controls: [],
});

I want to be able, after map initialization, to enable and disable each interaction.

I found the next code posted on stack (enable DragPan):

map.getInteractions().forEach((interaction) => {
    if (interaction instanceof ol.interaction.DragPan) {
        interaction.setActive(true);
    }
});

But the next one doesn't work:

map.getInteractions().forEach((interaction) => {
    if (interaction instanceof ol.interaction.AltShiftDragRotate) {
        interaction.setActive(true);
    }
});

The error: Right-hand side of 'instanceof' is not an object

Some help ?


Solution

  • Instead of using ol.interaction.defaults with false options (the option names should be in camelCase format) you should use

    var interactions = ol.interaction.defaults();
    interactions.forEach((interaction) => {
        interaction.setActive(false);
    });
    

    as setting the options false excludes some interactions instead of setting them disabled

    altShiftDragRotate is option name used to disable (or perhaps exclude) the DragRotate interaction, so the interaction class needed is ol.interaction.DragRotate

    interactions.forEach((interaction) => {
        if (interaction instanceof ol.interaction.DragRotate) {
            interaction.setActive(true);
        }
    });