Skip to content

Select 要素 by Hover ​

Select 要素 by Hover示例。 选择 矢量

在本示例中,Select 交互通过响应 pointermove 事件来进行选择

main.js
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
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>悬停选择要素</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
json
{
  "name": "select-hover-features",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}