原文链接及内容

在这个例子中,为地图对象注册了一个pointermove
监听器,以突出显示当前鼠标悬停的要素。
main.js
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import Fill from 'ol/style/Fill.js'; import GeoJSON from 'ol/format/GeoJSON.js'; import Map from 'ol/Map.js'; import Stroke from 'ol/style/Stroke.js'; import Style from 'ol/style/Style.js'; import VectorLayer from 'ol/layer/Vector.js'; import VectorSource from 'ol/source/Vector.js'; import View from 'ol/View.js';
const style = new Style({ fill: new Fill({ color: '#eeeeee', }), });
const vector = new VectorLayer({ source: new VectorSource({ url: 'https://openlayers.org/data/vector/ecoregions.json', format: new GeoJSON(), }), background: 'white', style: function (feature) { const color = feature.get('COLOR') || '#eeeeee'; style.getFill().setColor(color); return 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');
let selected = null; map.on('pointermove', function (e) { if (selected !== null) { selected.setStyle(undefined); selected = null; }
map.forEachFeatureAtPixel(e.pixel, function (f) { selected = f; selectStyle.getFill().setColor(f.get('COLOR') || '#eeeeee'); f.setStyle(selectStyle); return true; });
if (selected) { status.innerHTML = selected.get('ECO_NAME'); } else { status.innerHTML = ' '; } });
|
界面布局文件index.html
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <!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"> </span> <script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script> <script type="module" src="main.js"></script> </body> </html>
|