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 {always} from 'ol/events/condition.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Select from 'ol/interaction/Select.js';
import VectorLayer from 'ol/layer/Vector.js';
import {fromLonLat} from 'ol/proj.js';
import VectorSource from 'ol/source/Vector.js';
const select = new Select({
toggleCondition: always,
multi: true,
});
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,
}),
});
map.addInteraction(select);
const status = document.getElementById('status');
select.on('select', function () {
status.innerHTML =
' ' + select.getFeatures().getLength() + ' 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.7.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}