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?