Drawing 要素 样式
Drawing 要素 样式示例。 绘制 样式
本示例中的 Draw 交互使用了自定义绘制样式。从上方的下拉框中选择一种几何类型即可开始绘制。要结束绘制,请点击最后一个点。要对手绘线、多边形和圆启用手绘模式,请按住 Shift 键。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Draw from 'ol/interaction/Draw.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import OSM from 'ol/source/OSM.js';
import VectorSource from 'ol/source/Vector.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; // 全局变量,以便稍后移除
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new Draw({
source: source,
type: typeSelect.value,
style: styles[value],
});
map.addInteraction(draw);
}
}
/**
* 处理 change 事件。
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};
addInteraction();index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绘制要素样式</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">几何类型:</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>package.json
json
{
"name": "draw-features-style",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}