Javascript 绘制完成且新多边形添加到openlayers 3中的功能列表时触发事件

Javascript 绘制完成且新多边形添加到openlayers 3中的功能列表时触发事件,javascript,openlayers-3,Javascript,Openlayers 3,我正在尝试使用OpenLayers 3创建一个交互式地图,客户端可以在地图上绘制多边形,然后检索绘制的多边形的坐标。我在CodePEN上找到了一个很好的小教程,我正在使用它进行绘图交互。下面是我用来在地图上绘制新多边形的代码: var curMap = this; this.draw_interaction = new ol.interaction.Draw({ source: this.vectorLayer.getSource(), type: /** @type {ol.

我正在尝试使用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()
函数应为我返回一个数组,其中包含所有添加的多边形坐标。但不是这样做,它只返回在最后一个多边形之前添加的多边形。下面是该函数的代码:

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));
    }
}
Map.prototype.saveData=函数(数据类型){
var format=new ol.format[data_type](),data,curMap=this;
试一试{
数据=format.writeFeatures(curMap.vectorLayer.getSource().getFeatures());
}捕获(e){
警报(e.name+“:”+e.message);
返回;
}
如果(数据类型==='GeoJSON'){
log(JSON.parse(data));
data=JSON.parse(数据);

对于(var i=0;i当功能(真的)添加到
ol.source.Vector
而不是
draund
时,请收听,因此:

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

非常感谢,如果可能的话,我建议将其作为事件添加到绘图交互中。@CoreyAlix不同意。“once”仅表示处理程序在您正在收听的任何事件上被触发一次。因此OP将使用完全相同的场景,只有他的处理程序才会触发一次。“once”不触发“事件结束后”.它并不是每次都开火。