我需要在我的Web应用程序中添加一个功能,用于撤销上一个点。已经有一些解决方案,例如this可以在一定程度上处理这个问题:
var undo = false; // set this to true in the Esc key handler
var draw = new ol.interaction.Draw({
// ...
geometryFunction: function(coords, geom) {
if (!geom) {
geom = new ol.geom.LineString(null);
}
if (undo) {
if (coords.length > 1) {
coords.pop();
}
undo = false;
}
geom.setCoordinates(coords);
return geom;
}
});
但似乎有一个错误或问题我无法解决。
使用此plunker,您可以尝试我要解释的内容:
如果您用一些顶点画了一条线,然后按“ESC”撤销操作,直到线上的最后一个点被删除,然后在与刚才撤销的点相同位置结束或足够接近该位置,那么最后一段将被删除,为什么?
通过图例解释:
1- 画一条线段
我试了几次,这种情况确实会发生。如果您添加的点不靠近被移除的点,或者添加了多个点,则不会发生。
编辑
看起来OL3会检查几何图形的最后两个坐标,如果它们相同,则决定结束绘制会话并移除最后一个坐标。我尝试了以下代码:
function geometryChange(coordinates, geometry){
if (!geometry) {
geometry = new ol.geom.LineString(null);
}
if (undo){
var coords = geometry.getCoordinates();
console.info(coords);
console.info(coordinates);
var diff = coordinates.length - coords.length;
if (diff > 0) {
var lastCoordinates= coordinates[coordinates.length-1];
console.info(coordinates);
coordinates.splice(coordinates.length - (diff+1), diff,lastCoordinates);
console.info(coordinates);
coordinates.pop();
console.info(coordinates);
undo=false;
if (coords.length === 1){
undone=true;
lineStringdraw.finishDrawing();
undone=false;
var emptyFeature = vector2.getSource().getFeatures()[vector2.getSource().getFeatures().length-1];
vector2.getSource().removeFeature(emptyFeature);
featureID-=1;
}
}
}
//console.info(coordinates);
geometry.setCoordinates(coordinates);
//coordinates= geometry.getCoordinates();
return geometry;
}
结果更加有趣。当我撤销最后一个点时,如果我想在靠近那个点的位置添加一个点(不用双击完成线条),OL会认为绘图已经完成并触发drawend事件(我为某些目的使用了这个事件,但令人惊讶的是它无缘无故地被触发)。
removeLastPoint
。您应该依赖它。演示分叉的Plunker。 - Jonatas Walker