JSFiddle - React, Tailwind, and code Playground
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]))]);
var featuresinBox = [];
var selected = new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 0.4)'
}),
radius: 5,
stroke: new ol.style.Stroke({
color: '#FFFF00',
width: 1.25
})
})
});
var unselected = new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0.4)'
}),
radius: 5,
stroke: new ol.style.Stroke({
color: '#3399CC',
width: 1.25
})
})
});
box.on('boxend', function() {
featuresinBox = [];
featureLayer.getSource().forEachFeature(function(e) {
e.setStyle(unselected);
});
featureLayer.getSource().forEachFeatureInExtent(box.getGeometry().extent, function(e) {
featuresinBox.push(e);
e.setStyle(selected);
});
document.getElementById("msg").innerHTML = featuresinBox.length;
});