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.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import VectorLayer from 'ol/layer/Vector.js';
import {fromLonLat} from 'ol/proj.js';
import VectorSource from 'ol/source/Vector.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
const highlightStyle = new Style({
fill: new Fill({
color: '#EEE',
}),
stroke: new Stroke({
color: '#3399CC',
width: 2,
}),
});
const vector = new VectorLayer({
background: 'white',
source: new VectorSource({
url: 'https://openlayers.org/data/vector/us-states.json',
format: new GeoJSON(),
}),
});
const map = new Map({
layers: [vector],
target: 'map',
view: new View({
center: fromLonLat([-100, 38.5]),
zoom: 4,
multiWorld: true,
}),
});
const selected = [];
const status = document.getElementById('status');
map.on('singleclick', function (e) {
map.forEachFeatureAtPixel(e.pixel, function (f) {
const 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';
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select multiple Features</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<span id="status"> 0 selected features</span>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "select-multiple-features",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}