原文链接及内容

运行界面

一个使用绘制交互的示例。从下拉列表中选择一个几何类型开始绘制,要完成绘图,请单击最后一点(线段和多边形需要双击结束本次绘制)。若要激活直线、多边形和圆的徒手绘制,请按住Shift键。要删除直线或多边形的最后一个点,请按“撤消”(Undo)。

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
import Draw from 'ol/interaction/Draw.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {OSM, Vector as VectorSource} from 'ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';

const raster = new TileLayer({
source: new OSM(),
});

const source = new VectorSource({wrapX: false});

const vector = new VectorLayer({
source: source,
});

const map = new Map({
layers: [raster, vector],
target: 'map',
view: new View({
center: [-11000000, 4600000],
zoom: 4,
}),
});

const typeSelect = document.getElementById('type');

let draw; // global so we can remove it later
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new Draw({
source: source,
type: typeSelect.value,
});
map.addInteraction(draw);
}
}

/**
* Handle change event.
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};

document.getElementById('undo').addEventListener('click', function () {
draw.removeLastPoint();
});

addInteraction();

界面布局文件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
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Draw Features</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<div class="row">
<div class="col-auto">
<span class="input-group">
<label class="input-group-text" for="type">Geometry type:</label>
<select class="form-select" id="type">
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
<option value="Circle">Circle</option>
<option value="None">None</option>
</select>
<input class="form-control" type="button" value="Undo" id="undo">
</span>
</div>
</div>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<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>