OL3 Feature Hovering

This post demonstrates hovering over features on a map and setting their borders to blue. Basically this repurposes the OL3 Box Selection Demo to use an ol3.interaction.Select interaction instead of click/drag box interactions. There’s some notes at the bottom about using map.on('pointermove') for an alternative way of doing it.

This was as an answer to this Stack Overflow question.

Example

Move your mouse around. When you hover over a country, its border goes blue.

Script

var countries = new ol.source.Vector({
    url: '/public/misc/countries.geojson',
    format: new ol.format.GeoJSON()
});

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        new ol.layer.Vector({
            source: countries
        })
    ],
    renderer: 'canvas',
    target: 'map',
    view: new ol.View({
        center: [0, 0],
        zoom: 2
    })
});

var highlighter = new ol.interaction.Select({
    condition: ol.events.condition.pointerMove
});
map.addInteraction(highlighter);

An alternative approach could be to use the technique, which gives you a bit more control over styling (but does not unhover the features). It lets you access the feature directly if you want to manipulate it (eg get its coordinates, etc):

var red_outline = new ol.style.Style({
    stroke: new ol.style.Stroke({
        color: 'red',
        opacity: 1,
        width: 1
    })
})

map.on("pointermove", function(event) {
    var map = event.map;
    var feature = map.forEachFeatureAtPixel(
        event.pixel, function(feature, layer) {
            return feature
        }
    )
    if (feature) {
        feature.setStyle(red_outline)
    }
})