Tracing around a polygon
Tracing around a polygon示例。 绘制 追踪 矢量 吸附 topology
绘制(draw)交互提供了一个 trace 选项,用于启用围绕已有要素的描迹。本示例使用 traceSource 选项,从一个数据源描迹要素并将其添加到另一个数据源。第一次点击目标要素的边将开始描迹,第二次点击该边将停止描迹。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Draw from 'ol/interaction/Draw.js';
import Snap from 'ol/interaction/Snap.js';
import VectorLayer from 'ol/layer/Vector.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import ImageTile from 'ol/source/ImageTile.js';
import VectorSource from 'ol/source/Vector.js';
const raster = new TileLayer({
source: new ImageTile({
url: 'https://api.maptiler.com/maps/satellite/{z}/{x}/{y}.jpg?key=Get your own API key at https://www.maptiler.com/cloud/',
maxZoom: 20,
}),
});
// 本图层中的要素将作为吸附目标
const baseVector = new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url: 'data/geojson/fire.json',
}),
style: {
'fill-color': 'rgba(255, 0, 0, 0.3)',
'stroke-color': 'rgba(255, 0, 0, 0.9)',
'stroke-width': 0.5,
},
});
// 绘制的要素将添加到这里
const drawVector = new VectorLayer({
source: new VectorSource(),
style: {
'stroke-color': 'rgba(100, 255, 0, 1)',
'stroke-width': 2,
'fill-color': 'rgba(100, 255, 0, 0.3)',
},
});
const map = new Map({
layers: [raster, baseVector, drawVector],
target: 'map',
view: new View({
center: [-13378949, 5943751],
zoom: 11,
}),
});
let drawInteraction;
const snapInteraction = new Snap({
source: baseVector.getSource(),
});
const typeSelect = document.getElementById('type');
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
drawInteraction = new Draw({
type: value,
source: drawVector.getSource(),
trace: true,
traceSource: baseVector.getSource(),
style: {
'stroke-color': 'rgba(255, 255, 100, 0.5)',
'stroke-width': 1.5,
'fill-color': 'rgba(255, 255, 100, 0.25)',
'circle-radius': 6,
'circle-fill-color': 'rgba(255, 255, 100, 0.5)',
},
});
map.addInteraction(drawInteraction);
map.addInteraction(snapInteraction);
}
}
typeSelect.onchange = function () {
map.removeInteraction(drawInteraction);
map.removeInteraction(snapInteraction);
addInteraction();
};
addInteraction();index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>围绕多边形描迹</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>
<form>
<label for="type">几何类型 </label>
<select id="type">
<option value="Polygon">多边形</option>
<option value="LineString">线段</option>
<option value="None">无</option>
</select>
</form>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "tracing",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}