Selecting features
HTML
<script src="http://openlayers.org/en/v3.0.0/build/ol.js"></script>
<link rel="stylesheet" href="http://openlayers.org/en/v3.0.0/css/ol.css">
<div id="map" class="map"></div>
<span id="msg"></span>
CSS
.map {
width: 400px;
height: 400px;
}
JavaScript
var view = new ol.View({
center: [0, 0],
zoom: 3
})
var featureLayer = new ol.layer.Vector({
source: new ol.source.Vector()
});
var box = new ol.interaction.DragBox({
condition: ol.events.condition.shiftKeyOnly,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
})
})
})
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
featureLayer,
],
view: view,
interactions: ol.interaction.defaults().extend([box])
});
featureLayer.getSource().addFeatures([new ol.Feature(new ol.geom.Point([0, 0])), new ol.Feature(new ol.geom.Point([100000, 2000000])), new ol.Feature(new ol.geom.Point([500000, 1000000])), new ol.Feature(new ol.geom.Point([1000000, 65000])), new ol.Feature(new ol.geom.Point([-1000000, 2000000])), new ol.Feature(new ol.geom.Point([-100000, -2000000]))]);
box.on('boxend', function() {
var featuresinBox = [];
featureLayer.getSource().forEachFeature(function(e) {
if (ol.extent.containsCoordinate(box.getGeometry().extent, e.getGeometry().getCoordinates())) {
featuresinBox.push(e);
}
});
document.getElementById("msg").innerHTML = featuresinBox.length;
});