Box selection example

Using a DragBox interaction to select features.

This example shows how to use a DragBox interaction to select features. Selected features are added to the feature overlay of a select interaction (ol.interaction.Select) for highlighting.

Use SHIFT+drag to draw boxes.

DragBox, feature, selection, box
<!DOCTYPE html>
<html>
<head>
<title>Box selection example</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://openlayers.org/en/v3.8.2/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.8.2/build/ol.js"></script>

</head>
<body>
<div class="container-fluid">

<div class="row-fluid">
  <div class="span12">
    <div id="map" class="map"></div>
  </div>
  <div class="span4 offset4 pull-right">
    <div id="info" class="alert alert-success">
      &nbsp;
    </div>
  </div>
</div>

</div>
<script>
var vectorSource = new ol.source.Vector({
  url: 'data/geojson/countries.geojson',
  format: new ol.format.GeoJSON()
});


var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Vector({
      source: vectorSource
    })
  ],
  renderer: 'canvas',
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

// a normal select interaction to handle click
var select = new ol.interaction.Select();
map.addInteraction(select);

var selectedFeatures = select.getFeatures();

// a DragBox interaction used to select features by drawing boxes
var dragBox = new ol.interaction.DragBox({
  condition: ol.events.condition.shiftKeyOnly,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: [0, 0, 255, 1]
    })
  })
});

map.addInteraction(dragBox);

var infoBox = document.getElementById('info');

dragBox.on('boxend', function(e) {
  // features that intersect the box are added to the collection of
  // selected features, and their names are displayed in the "info"
  // div
  var info = [];
  var extent = dragBox.getGeometry().getExtent();
  vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
    selectedFeatures.push(feature);
    info.push(feature.get('name'));
  });
  if (info.length > 0) {
    infoBox.innerHTML = info.join(', ');
  }
});

// clear selection when drawing a new box and when clicking on the map
dragBox.on('boxstart', function(e) {
  selectedFeatures.clear();
  infoBox.innerHTML = '&nbsp;';
});
map.on('click', function() {
  selectedFeatures.clear();
  infoBox.innerHTML = '&nbsp;';
});

</script>
</body>
</html>