替换“绘制”上绘制的几何图形

Replacing the drawn geometry on 'drawend'

本文关键字:绘制 几何图形 替换      更新时间:2023-09-26

我要做的是在绘制特征后替换或更改其几何形状,例如:我画了一条线,画完后,我用Turf.js修改几何形状,在绘制的线周围做一个缓冲区,并显示缓冲线(多边形)而不是线。

var draw = new ol.interaction.Draw({
    source: vectorSource,
    type: 'LineString'
});
draw.on('drawend', function(e) {
    //Sending the LineString to a Turf function with a buffer value and getting a Polygon in return
    var bfc = bufferedFeatureCollection(100, e.feature);
    //Replacing the LineString geometry with a Polygon geometry
    e.feature.setGeometry(bfc[0].getGeometry());
    //Removes and terminates the draw action.... 
    map.removeInteraction(this);
});

现在从console.log(),我可以看到feature.geometry已经从ol.geom.linestring改为ol.geom.polygon。但是在地图上,我仍然看到一条线正在显示。

我做错了什么?

在将功能添加到 ol.source.Vector 后进行这些修改,因此:

vectorSource.on('addfeature', function(evt){
    //Sending the LineString to a Turf function with a buffer value and getting a Polygon in return
    var bfc = bufferedFeatureCollection(100, evt.feature);
    //Replacing the LineString geometry with a Polygon geometry
    evt.feature.setGeometry(bfc[0].getGeometry());
    //Removes and terminates the draw action.... 
    map.removeInteraction(draw);
});

我犯的错误是缓冲区值太低而无法被视为缓冲区,因此我只看到了一条线(即使它是多边形),我不得不从100 to 10000000提高缓冲区值......

因此,在draw.on('drawend')vectorSource.on('addfeature')中都可以替换已绘制的几何图形。

编辑:

为了答案的完整性。我不得不从100 to 10000000更改缓冲区的原因是我忘记将几何转换为EPSG:4326,然后再将其传递给 Turf 函数。草皮仅适用于EPSG:4326

var draw = new ol.interaction.Draw({
    source: vectorSource,
    type: 'LineString'
});
draw.on('drawend', function(e) {
    e.feature.getGeometry().transform('EPSG:3857', 'EPSG:4326');
    var bfc = bufferedFeatureCollection(radius, e.feature);
    bfc[0].getGeometry().transform('EPSG:4326', 'EPSG:3857');
    e.feature.setGeometry(bfc[0].getGeometry());
    //Removes and terminates the draw action....
    map.removeInteraction(this); 
});