Edit

Select Features by Hover

select4 vector85

 

Example of selecting features by hovering.

In this example, the Select interaction reacts to the pointermove event for selection

main.js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {pointerMove} from 'ol/events/condition.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Select from 'ol/interaction/Select.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';

const style = new Style({
  fill: new Fill({
    color: '#eeeeee',
  }),
});

function colorStyle(style) {
  return function (f) {
    style.getFill().setColor(f.get('COLOR') || '#eeeeee');
    return style;
  };
}

const vector = new VectorLayer({
  source: new VectorSource({
    url: 'https://openlayers.org/data/vector/ecoregions.json',
    format: new GeoJSON(),
  }),
  background: 'white',
  style: colorStyle(style),
});

const map = new Map({
  layers: [vector],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

const selectStyle = new Style({
  fill: new Fill({
    color: '#eeeeee',
  }),
  stroke: new Stroke({
    color: 'rgba(255, 255, 255, 0.7)',
    width: 2,
  }),
});

const status = document.getElementById('status');
const select = new Select({
  condition: pointerMove,
  style: colorStyle(selectStyle),
});
map.addInteraction(select);

select.on('select', function (e) {
  if (e.selected.length > 0) {
    status.innerHTML = e.selected[0].get('ECO_NAME');
  } else {
    status.innerHTML = ' ';
  }
});
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Select Features by Hover</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <span id="status">&nbsp;</span>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
{
  "name": "select-hover-features",
  "dependencies": {
    "ol": "10.7.0"
  },
  "devDependencies": {
    "vite": "^3.2.3"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}