Example of selecting features by hovering.
In this example, a listener is registered on the map's pointermove
to highlight the currently hovered feature.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Select Features by Hover</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"></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
})
});
var selected = null;
var 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 = ' ';
}
});
{
"name": "select-hover-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"
}
}