原文链接及内容

运行界面

本例中的绘图交互使用自定义绘图样式。从上面的下拉列表中选择一个几何类型开始绘图。要完成绘图,请单击最后一点(绘制线和面要双击结束)。要激活线条、多边形和圆形的手绘,请按住Shift键。

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
73
74
75
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 styles = {
Point: {
'circle-radius': 5,
'circle-fill-color': 'red',
},
LineString: {
'circle-radius': 5,
'circle-fill-color': 'red',
'stroke-color': 'yellow',
'stroke-width': 2,
},
Polygon: {
'circle-radius': 5,
'circle-fill-color': 'red',
'stroke-color': 'yellow',
'stroke-width': 2,
'fill-color': 'blue',
},
Circle: {
'circle-radius': 5,
'circle-fill-color': 'red',
'stroke-color': 'blue',
'stroke-width': 2,
'fill-color': 'yellow',
},
};

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,
style: styles[value],
});
map.addInteraction(draw);
}
}

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

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drawing Features Style</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>
</span>
</div>
</div>

<script type="module" src="main.js"></script>
</body>
</html>