Example of selecting multiple features.
In this example, a listener is registered on the map's singleclick
event to add and remove features from an array.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Select multiple Features</title>
<!-- 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>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<span id="status"> 0 selected features</span>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import GeoJSON from 'ol/format/GeoJSON';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import OSM from 'ol/source/OSM';
import VectorSource from 'ol/source/Vector';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
var raster = new TileLayer({
source: new OSM()
});
var highlightStyle = new Style({
fill: new Fill({
color: 'rgba(255,255,255,0.7)'
}),
stroke: new Stroke({
color: '#3399CC',
width: 3
})
});
var vector = new VectorLayer({
source: new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON()
})
});
var map = new Map({
layers: [raster, vector],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
multiWorld: true
})
});
var selected = [];
var status = document.getElementById('status');
map.on('singleclick', function(e) {
map.forEachFeatureAtPixel(e.pixel, function(f) {
var selIndex = selected.indexOf(f);
if (selIndex < 0) {
selected.push(f);
f.setStyle(highlightStyle);
} else {
selected.splice(selIndex, 1);
f.setStyle(undefined);
}
});
status.innerHTML = ' ' + selected.length + ' selected features';
});
{
"name": "select-multiple-features",
"dependencies": {
"ol": "6.1.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}