原文链接及内容

调用ol/proj
模块中的useGeography
函数可以使地图视图使用地理坐标(即使视图投影不是地理坐标)。
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 70 71 72
| import GeoJSON from 'ol/format/GeoJSON.js'; import VectorLayer from 'ol/layer/Vector.js'; import VectorSource from 'ol/source/Vector.js'; import {Draw, Modify, Select, Snap} from 'ol/interaction.js'; import {Map, View} from 'ol/index.js'; import {useGeographic} from 'ol/proj.js';
useGeographic();
const source = new VectorSource({ url: 'https://openlayers.org/data/vector/us-states.json', format: new GeoJSON(), });
const map = new Map({ target: 'map', layers: [ new VectorLayer({ background: 'white', source: source, }), ], view: new View({ center: [-100, 38.5], zoom: 4, }), });
const select = new Select();
const modify = new Modify({ features: select.getFeatures(), });
const draw = new Draw({ type: 'Polygon', source: source, });
const snap = new Snap({ source: source, });
function removeInteractions() { map.removeInteraction(modify); map.removeInteraction(select); map.removeInteraction(draw); map.removeInteraction(select); }
const mode = document.getElementById('mode'); function onChange() { removeInteractions(); switch (mode.value) { case 'draw': { map.addInteraction(draw); map.addInteraction(snap); break; } case 'modify': { map.addInteraction(select); map.addInteraction(modify); map.addInteraction(snap); break; } default: { } } } mode.addEventListener('change', onChange); onChange();
|
界面布局文件index.html
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Geographic Editing</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> <select id="mode"> <option value="modify">select a feature to modify</option> <option value="draw">draw new features</option> </select> <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>
|