使用 ol/interaction/Draw 交互的示例。
使用绘制交互的示例。从上方下拉菜单中选择一种几何类型开始绘制。要完成绘制,请点击最后一个点。要对线、多边形和圆激活自由绘制模式,请按住 Shift 键。要删除线或多边形的最后一个点,请按"撤销"。
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 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();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Draw Features</title>
<link rel="stylesheet" href="https://openlayers.vip/apidoc/resources/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>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "draw-features",
"dependencies": {
"ol": "10.9.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}