Ada*_*yai 3 javascript 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');
});
Run Code Online (Sandbox Code Playgroud)
可以看出,整个代码都包含在一个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));
}
}
Run Code Online (Sandbox Code Playgroud)
我假设刚刚绘制的新多边形特征被添加到特征列表中,就在this.saveData()函数触发之后,这就是为什么最后添加的多边形从未被捕获的原因.是否有一种方法,一个事件监听器可能会this.saveData()在将新功能添加到地图后立即强制触发该功能?
Jon*_*ker 12
在(实际)添加功能时监听,ol.source.Vector而不是drawend:
this.vectorLayer.getSource().on('addfeature', function(event){
// ...
});
Run Code Online (Sandbox Code Playgroud)