用这个例子: https://openlayers.org/en/latest/examples/draw-and-modify-features.html
我尝试创建一个多边形,但我希望它在多边形完成后消失。
有人可以帮助我吗?
谢谢:)
只需在创建交互时删除源:
draw = new Draw({
type: 'Polygon'
});
如果未为绘制要素设置目标源,则面将在完成后消失(否则将添加到源中(。 侦听绘制事件以获取多边形。
如果我理解正确,您希望在用户几何图形绘制完成后删除绘制交互。就像@Anatoly评论中提到的一样,您可以使用drawend
事件来删除交互。
看看我为你做的例子,
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
<title>End Draw Interaction After Draw</title>
</head>
<body>
<div>
<button id="startDraw">Start Draw</button>
<button id="endDraw">End Draw</button>
</div>
<div id="map" class="map"></div>
<script type="text/javascript">
// vector layer
var source = new ol.source.Vector();
var vector = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
})
})
});
// map
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vector
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
// buttons
var startDrawBtn = document.getElementById('startDraw');
var endDrawBtn = document.getElementById('endDraw');
endDrawBtn.disabled = true;
// interaction
var draw = new ol.interaction.Draw({
source: source,
type: 'Polygon'
});
var snap = new ol.interaction.Snap({source: source});
function endInteractions() {
map.removeInteraction(draw);
map.removeInteraction(snap);
startDrawBtn.disabled = false;
endDrawBtn.disabled = true;
}
function startInteractions() {
startDrawBtn.disabled = true;
endDrawBtn.disabled = false;
map.addInteraction(draw);
map.addInteraction(snap);
draw.on('drawend', evt => {
// console.log(evt.feature);
endInteractions();
});
}
startDrawBtn.addEventListener('click', startInteractions);
endDrawBtn.addEventListener('click', endInteractions);
</script>
</body>
</html>