当绘制完成并将新多边形添加到 openlayers 3 中的要素列表时触发事件

Fire an event when draw finishes and new polygon is added to the features list in openlayers 3

我正在尝试使用 OpenLayers 3 创建交互式地图,客户端可以在地图上绘制多边形,然后检索绘制的多边形的坐标。我在 CodePEN 上找到了一个不错的小教程,我将其用于绘图交互。这是我用来在地图上绘制新多边形的代码:

 var curMap = this;

 this.draw_interaction = new ol.interaction.Draw({
   source: this.vectorLayer.getSource(),
   type: /** @type {ol.geom.GeometryType} */ ('Polygon')
 });

 this.map.addInteraction(this.draw_interaction);

 // when a new feature has been drawn...
 this.draw_interaction.on('drawend', function(event) {
   curMap.map.removeInteraction(curMap.draw_interaction);
   var id = 'addedpoly '+curMap.vectorLayer.getSource().getFeatures().length;

   event.feature.setId(id);
   event.feature.setStyle(curMap.defaultPolyStyle);

   console.log(event.feature);
   curMap.saveData('GeoJSON'); 
 });

可以看出,整个代码都包装在一个 javascript 对象中,我在其中存储了绘图所需的不同类型的值。添加新多边形后,this.saveData() 函数应该 return 一个数组,其中包含所有添加的多边形坐标。但不是这样做,它只是 returns 在最后一个之前添加的多边形。这是该函数的代码:

Map.prototype.saveData = function (data_type) {
    var format = new ol.format[data_type](), data, curMap = this;

    try {
        data =    format.writeFeatures(curMap.vectorLayer.getSource().getFeatures());
    } catch (e) {
        alert(e.name + ": " + e.message);
        return;
    }

    if (data_type === 'GeoJSON') {
        console.log(JSON.parse(data));
        data=JSON.parse(data);
        for (var i=0;i<data.features.length ;i++ )
        {
            if (data.features[i].geometry.type != 'Point') console.log(i, data.features[i]);
        }
        console.log(JSON.stringify(data, null, 4));
    } else {
        var serializer = new XMLSerializer();
        console.log(serializer.serializeToString(data));
    }
}

我假设刚刚绘制的新多边形特征正在添加到特征列表中,就在 this.saveData() 函数触发之后,这就是为什么最后添加的多边形从未被捕捉到。有没有办法,也许是事件侦听器,在向地图添加新功能后立即强制触发 this.saveData() 功能?

当功能被(真正)添加到 ol.source.Vector 而不是 drawend 时收听,所以:

this.vectorLayer.getSource().on('addfeature', function(event){
  // ...
});