如何使用 OpenLayers 将属性插入 WFS?

How to insert attributes into a WFS using OpenLayers?

所以我有一个 运行 的网络应用程序,它能够通过从 Geoserver 获取数据来向现有的 Postgis 表添加点和线。我需要添加以下一项特定功能:

我想让用户也可以在地图界面上为每个点添加属性信息。比如,他们在地图上绘制的每个点,都需要允许用户在列中输入一些文本数据。

我尝试阅读这里的一些问题,但其中 none 提供了点向量层的解决方案。

如何操作?

我加载和发布 WFS 点特征的位是:

var vectorSource2 = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url2 =    'http://localhost:8080/geoserver/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=BFTchambers:chamber2&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures2' +
'&bbox=' + extent.join(',');
$.ajax({url: url2, dataType: 'jsonp', jsonp: false})
.done(function(response) {
    pointWFS = new ol.format.WFS(),
    sourceVector2.addFeatures(pointWFS.readFeatures(response))
    });
},
strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({
maxZoom: 20
})),
});

window.loadFeatures2 = function(response) {
console.log("Point features were drawn");
vectorSource2.addFeatures(geojsonFormat.readFeatures(response));
};
var formatWFS2 = new ol.format.WFS();
var pointGML = new ol.format.GML({
featureNS: 'http://geoserver.org/bftchamber',
featureType: 'chamber2',
});

var pointWFS = function(p,f) {
switch(p) {
case 'insert':
    node = formatWFS2.writeTransaction([f],null,null,pointGML);
    break;
case 'update':
    node = formatWFS2.writeTransaction(null,[f],null,pointGML);
    break;
case 'delete':
    node = formatWFS2.writeTransaction(null,null,[f],pointGML);
    break;
}
s = new XMLSerializer();
str = s.serializeToString(node);
$.ajax('http://localhost:8080/geoserver/wfs',{
    type: 'POST',
    dataType: 'xml',
    processData: false,
    contentType: 'text/xml',
    data: str
    }).done();
    console.log(" point features were posted to server");
}
case 'btnDrawPoint':
    interaction = new ol.interaction.Draw({
        type: 'Point',
        source: layerVector.getSource()
    });
    map.addInteraction(interaction);
    interaction.on('drawend', function(e) {
        pointWFS('insert',e.feature);
    });
    break;

只需按照@bartvde 建议的方式添加属性即可。

例如使用你自己的例子

interaction.on('drawend', function(e) { //pass an attribute to the feature var featureWithAttribute = e.feature.set('foo', 'bar'); pointWFS('insert',featureWithAttribute); });

因此,此修改将发送一个包含几何的特征,以及一个列名称 foo 的属性,其中包含 bar 的值。

现在,如果您希望用户输入文本:

  interaction.on('drawend', function(e) {
    //pass an attribute to the feature
    var myAttrValue = prompt("Enter Attribute", "");
    var myFeature= e.feature;
    if (myAttrValue != null) {
     myFeature.set('foo', myAttrValue);
     }

    pointWFS('insert',myFeature);
});

当然这只是一个使用promt默认js函数的例子。但是您可以使用 UI api 来获得类似的行为