Extent Interaction

Using an Extent interaction to draw an extent.

This example shows how to use an Extent interaction to draw a modifiable extent.

Use Shift+Drag to draw an extent. Shift+Drag on the corners or edges of the extent to resize it. Shift+Click off the extent to remove it.

<!DOCTYPE html>
<html>
  <head>
    <title>Extent Interaction</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>

  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
      import Map from 'ol/Map.js';
      import View from 'ol/View.js';
      import {platformModifierKeyOnly} from 'ol/events/condition.js';
      import GeoJSON from 'ol/format/GeoJSON.js';
      import ExtentInteraction from 'ol/interaction/Extent.js';
      import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
      import {OSM, Vector as VectorSource} from 'ol/source.js';

      var vectorSource = new VectorSource({
        url: 'data/geojson/countries.geojson',
        format: new GeoJSON()
      });

      var map = new Map({
        layers: [
          new TileLayer({
            source: new OSM()
          }),
          new VectorLayer({
            source: vectorSource
          })
        ],
        target: 'map',
        view: new View({
          center: [0, 0],
          zoom: 2
        })
      });

      var extent = new ExtentInteraction({
        condition: platformModifierKeyOnly
      });
      map.addInteraction(extent);
      extent.setActive(false);

      //Enable interaction by holding shift
      window.addEventListener('keydown', function(event) {
        if (event.keyCode == 16) {
          extent.setActive(true);
        }
      });
      window.addEventListener('keyup', function(event) {
        if (event.keyCode == 16) {
          extent.setActive(false);
        }
      });
    </script>
  </body>
</html>