[GIS] ZoomBox in Openlayers 3/4

openlayers

I want to bind ZoomBox function to a toolbar button to active and deactivate, its default activator is Shift key. Is there a way to activate without pressing the shift key?

In OpenLayers 2 I could add the ZoomBox function using:

self.zb = new OpenLayers.Control.ZoomBox({
        title: "Zoom box: zoom clicking and dragging",
        text: "Zoom"
});
self.map.addControl(self.zb);

and to active:

this.zb.activate();

I can't find the ZoomBox objects under ol.control class in Openlayers 4. Is there a ZoomBox equivalent or alternative in OpenLayers 4. If not how can I do this programmatically?

Best Answer

The zoombox control you are looking for has been changed to ol.interaction.DragZoom

http://openlayers.org/en/latest/apidoc/ol.interaction.DragZoom.html

You can configure the toolbar button to add or remove the interaction using addInteraction()or removeInteraction() but this method still needs the default shift key to activate.

Edit: Interaction conditions can be modified using ol.events.condition. You can find more information on this in the api doc here

Adding the ol.events.condition.always should help you in what you are trying to achieve.

var dragZoom = new ol.interaction.DragZoom({
  condition: ol.events.condition.always
});
map.addInteraction(dragZoom);

You can add or remove the interaction by adding an onclick event to a toggle button

var toggleState = 0;

$("#toggleZoom").click(function () {

    if( toggleState == 0) {
        map.addInteraction(dragZoom);
        toggleState = 1;
    }
    else {
        map.removeInteraction(dragZoom);
        toggleState = 0;
    }

});
Related Question