Example of selecting features by hovering.
In this example, a listener is registered on the map's pointermove
to highlight the currently hovered feature.
import 'ol/ol.css';
import Fill from 'ol/style/Fill';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
const style = new Style({
fill: new Fill({
color: '#eeeeee',
}),
});
const vector = new VectorLayer({
source: new VectorSource({
url: 'https://openlayers.org/data/vector/ecoregions.json',
format: new GeoJSON(),
}),
background: 'white',
style: function (feature) {
const color = feature.get('COLOR') || '#eeeeee';
style.getFill().setColor(color);
return style;
},
});
const map = new Map({
layers: [vector],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const selectStyle = new Style({
fill: new Fill({
color: '#eeeeee',
}),
stroke: new Stroke({
color: 'rgba(255, 255, 255, 0.7)',
width: 2,
}),
});
const status = document.getElementById('status');
let selected = null;
map.on('pointermove', function (e) {
if (selected !== null) {
selected.setStyle(undefined);
selected = null;
}
map.forEachFeatureAtPixel(e.pixel, function (f) {
selected = f;
selectStyle.getFill().setColor(f.get('COLOR') || '#eeeeee');
f.setStyle(selectStyle);
return true;
});
if (selected) {
status.innerHTML = selected.get('ECO_NAME');
} else {
status.innerHTML = ' ';
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select Features by Hover</title>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep@1.0.6/dist/elm-pep.js"></script>
<!-- The lines below are only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,TextDecoder"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.18.3/minified.js"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<span id="status"> </span>
<script src="main.js"></script>
</body>
</html>
{
"name": "select-hover-features",
"dependencies": {
"ol": "6.13.1-dev"
},
"devDependencies": {
"parcel": "^2.0.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
}
}