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

余生长醉 提交于 2020-01-03 20:05:10

问题


I am trying to create an interactive map with OpenLayers 3, where the client can draw polygons on the map, and then retrieve the coordinates of the polygons which were drawn. I've found a nice little tutorial on CodePEN, which I am using for the draw interaction. Here's the code I use to draw a new polygon on the map:

 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'); 
 });

As it can be seen, the whole code is wrapped in a javascript object, in which I store different kind of values needed for the drawing. The this.saveData() function should return an array for me after a new polygon is added, with ALL the added polygons coordinates. But instead of doing this, it only returns the polygons that were added before the last one. Here's the code for that function:

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));
    }
}

I presume that the new polygon feature, which was just drawn, is being added to the feature list, just after the this.saveData() function fires, that's why the last added polygon is never catched. Is there a way, an event listener maybe, to force the firing of the this.saveData() function, right after a new feature was added to the map?


回答1:


Listen when the feature is (really) added to ol.source.Vector instead of drawend, so:

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


来源:https://stackoverflow.com/questions/39207319/fire-an-event-when-draw-finishes-and-new-polygon-is-added-to-the-features-list-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!