原文链接及内容

在这个例子中,为地图对象注册了一个的singleclick
监听器,用于从数组中添加和删除要素。
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
| 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'; import {fromLonLat} from 'ol/proj.js';
const highlightStyle = new Style({ fill: new Fill({ color: '#EEE', }), stroke: new Stroke({ color: '#3399CC', width: 2, }), });
const vector = new VectorLayer({ background: 'white', source: new VectorSource({ url: 'https://openlayers.org/data/vector/us-states.json', format: new GeoJSON(), }), });
const map = new Map({ layers: [vector], target: 'map', view: new View({ center: fromLonLat([-100, 38.5]), zoom: 4, multiWorld: true, }), });
const selected = [];
const status = document.getElementById('status');
map.on('singleclick', function (e) { map.forEachFeatureAtPixel(e.pixel, function (f) { const selIndex = selected.indexOf(f); if (selIndex < 0) { selected.push(f); f.setStyle(highlightStyle); } else { selected.splice(selIndex, 1); f.setStyle(undefined); } });
status.innerHTML = ' ' + selected.length + ' selected features'; });
|
界面布局文件index.html
代码如下: