OpenLayers Feature Highlighting on Mouse Hover
Highlighting vector features when the cursor passes over them can be achieved through two distinct mechanisms in OpenLayers.
Method 1: Built-in Select Interaction
The Select interaction can be configured to trigger on cursor movement rather than a click by specifying the pointerMove condition.
const hoverInteraction = new ol.interaction.Select({
condition: ol.events.condition.pointerMove,
hitTolerance: 2
});
map.addInteraction(hoverInteraction);
To react to the selection changes, listen to the select event:
hoverInteraction.on('select', (evt) => {
const chosenFeatures = evt.selected;
if (chosenFeatures.length > 0) {
console.log('Feature entered:', chosenFeatures);
} else {
console.log('Feature exited');
}
});
Method 2: Manual Pixel Detection and Styling
Instead of relying on the Select interaction, you can manual detect faetures at the cursor's pixel coordinates and apply styles directly.
const highlightAppearance = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 100, 50, 0.7)'
}),
stroke: new ol.style.Stroke({
color: 'darkred',
width: 3
}),
image: new ol.style.Circle({
radius: 8,
fill: new ol.style.Fill({
color: 'rgba(255, 100, 50, 0.7)'
}),
stroke: new ol.style.Stroke({
color: 'darkred',
width: 2
})
})
});
let currentlyHovered = null;
function processHoverEvent(mapEvent) {
const targets = map.getFeaturesAtPixel(mapEvent.pixel, {
hitTolerance: 4
});
if (targets && targets.length > 0) {
const target = targets[0];
if (currentlyHovered !== target) {
if (currentlyHovered) currentlyHovered.setStyle(undefined);
currentlyHovered = target;
currentlyHovered.setStyle(highlightAppearance);
}
} else if (currentlyHovered) {
currentlyHovered.setStyle(undefined);
currentlyHovered = null;
}
}
map.on('pointermove', processHoverEvent);