OpenLayers zoom in and zoom out by box selection

OpenLayers zoom in and zoom out by box selection

In this tutorial, we will create small functionality where we will zoom in to and zoom out from map by drawing a box selection as shown in above GIF. This tool is one of the most common tool in GIS map.

To get full source code for this tutorial, click here.

To check the live demo for this tutorial, click here.

This tool is fairly simple to implement. In fact, it is already present in OpenLayers. You just have to enable it.
To implement zoom in/out by box selection, we will use one the interaction available in OpenLayers. The interaction we will be using is ol.interaction.DragZoom. We will create zoom in/out by box selection step by step. Please refer below code snippet:

  1. Define OpenLayers map(Line numbers: 2-13)
  2. Define zoom_by_box function (Line number: 24-32). In this function we are creating DragZoom interaction and adding it to map. Once this interaction is activated, it will allow us to draw a box and will be automatically zoom in to it’s extent.
    If you want to reverse the functionality meaning to zoom out on box selection, we will pass out property (line number 29) as true. Then it will zoom out from map on box selection.
  3. At line number 36 and 44, we listening to zoom in and zoom out button click event and calling zoom_by_box function accordingly.

I hope this tutorial will create a good foundation for you. If you want tutorials on another GIS topic or you have any queries, please send an email at

We also offer freelancing services. Please email us at for any query.

1 thought on “OpenLayers zoom in and zoom out by box selection”

  1. Very good example. I would like one more button, to remove this iteration of box selection, to continue doing other activities on the map. How should I proceed? Only this code did not work:
    if (map.getInteractions().getArray().length > default_interactions_size) {

Leave a ReplyCancel reply