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 OSM from 'ol/source/OSM';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
const raster = new TileLayer({
source: new OSM(),
});
const highlightStyle = new Style({
fill: new Fill({
color: 'rgba(255,255,255,0.7)',
}),
stroke: new Stroke({
color: '#3399CC',
width: 3,
}),
});
const vector = new VectorLayer({
source: new VectorSource({
url: 'data/geojson/countries.geojson',
format: new GeoJSON(),
}),
});
const map = new Map({
layers: [raster, vector],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
let selected = null;
const status = document.getElementById('status');
map.on('pointermove', function (e) {
if (selected !== null) {
selected.setStyle(undefined);
selected = null;
}
map.forEachFeatureAtPixel(e.pixel, function (f) {
selected = f;
f.setStyle(highlightStyle);
return true;
});
if (selected) {
status.innerHTML = ' Hovering: ' + selected.get('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"></script>
<!-- The line below is 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,URL,TextDecoder,Number.isInteger"></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.6.1"
},
"devDependencies": {
"parcel": "^2.0.0-beta.1"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
}
}