在' drawend'上替换绘制的几何图形。

时间:2016-01-23 14:00:17

标签: javascript openlayers-3

我要做的是在绘制后更换或更改要素的几何图形。例如:我绘制一条线,在绘制完成后,我用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。但在地图上我仍然看到一条线正在显示。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

将此功能添加到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);
});

答案 1 :(得分:0)

我犯的错误是缓冲区值太低而不能被视为缓冲区因此我只看到一条线(甚至是多边形)我不得不从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); 
});