OL5.3 | Hover highlight each feature
by Dennis Bauszus
HTML
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css">
<div id="map" class="map"></div>
CSS
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
border: 0;
}
.map {
height: 100%;
width: 100%;
}
JavaScript
const layerOSM = new ol.layer.Tile({
source: new ol.source.OSM()
});
const layerPoint = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Point([-11407000, 2520000])
})]
})
});
const layerLine = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.LineString([
[-11913296, 3188998],
[-11210043, 1737457]
])
})]
})
});
const layerPoly = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Polygon([
[
[-12550727, 2281352],
[-11168471, 3244427],
[-10867077, 1986886],
[-12550727, 2281352]
]
])
})]
})
});
const map = new ol.Map({
target: 'map',
controls: [],
layers: [layerOSM, layerPoly, layerPoint, layerLine],
view: new ol.View({
center: [-11407508, 2520388],
zoom: 5
})
});
let highlightedFeatures = [];
map.on('pointermove', function(e) {
highlightedFeatures.forEach(f => f.setStyle(null));
highlightedFeatures = [];
map.forEachFeatureAtPixel(e.pixel, f => {
f.setStyle(new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0d47a1',
width: 2
}),
image: new ol.style.Circle({
radius: 5.5,
stroke: new ol.style.Stroke({
color: '#0d47a1',
width: 2
})
})
}));
highlightedFeatures.push(f);
});
});