最近在做一个使用openlayes+geoserver+postgis实现wfs编辑要素的功能,踩了一些坑,总结了几点记录下来。
WFS序列化时的参数
一个是featureType属性,它必须是wms服务的名称,还有featureNS,它表示的是要素的工作区的命名空间URI。
// 把修改提交到服务器端
function modifyWfs(features, type) {
const WFSTSerializer = new WFS();
const featObject = WFSTSerializer.writeTransaction(null,
features, null, {
// 这个值是wms图层名称
featureType: type.split(':')[1],
// 这个值必须为创建工作区时的命名空间URI
featureNS: 'http://www.fujianai.com',
srsName: 'EPSG:4326'
});
// 转换为xml内容发送到服务器端
const serializer = new XMLSerializer();
const featString = serializer.serializeToString(featObject);
const request = new XMLHttpRequest();
request.open('POST', 'http://127.0.0.1:8020/geoserver/fujianai/wfs?service=WFS');
// 指定内容为xml类型
request.setRequestHeader('Content-Type', 'application/xml');
request.send(featString);
}
编辑要素的GeometryName的问题
注意一下要素的geometryName的问题,看一下wfs服务的GeoJson格式下geometry_name属性,如果geometry_name对不上,就会抛出错误。
openlayers的默认的geometryName是geometry。
<ows:Exception exceptionCode="InvalidParameterValue">
<ows:ExceptionText>No such property: geometry</ows:ExceptionText>
</ows:Exception>
解决方案就是重新设置一下geometryName属性。
// 保存已经编辑的要素
function onSave(type) {
if (this.$modifiedFeatures && this.$modifiedFeatures.getLength() > 0) {
// 得到要素副本
const modifiedFeature = this.$modifiedFeatures.item(0).clone();
// 设置ID
modifiedFeature.setId(this.$modifiedFeatures.item(0).getId());
// 调换经纬度坐标,以符合wfs协议中经纬度的位置
modifiedFeature.getGeometry().applyTransform(function(flatCoordinates, flatCoordinates2, stride) {
for (let j = 0; j < flatCoordinates.length; j += stride) {
const y = flatCoordinates[j];
flatCoordinates[j] = flatCoordinates[j + 1];
flatCoordinates[j + 1] = y;
}
})
// 必须重新设置Geometry的名称, 对应的是wfs服务的geometry_name,如果是postgis就是geom
modifiedFeature.setGeometryName('geom')
modifyWfs.call(this,[modifiedFeature], type);
}
}
geoserver 的权限问题
默认情况下,在geoserver的Security下的Data选项里的写的最高权限没有开启, 导致wfs编辑要素保存的时候提示某某图层是只读的。
<ows:Exception exceptionCode="NoApplicableCode">
<ows:ExceptionText>
{www.fujianai.com}result_2013_water_202134_37006edddbc5f67c8b5035849b097b29 is read-only
</ows:ExceptionText>
</ows:Exception>
解决办法就是在geoserver的Security下的Data选项里选择写的权限编辑选中允许最高权限。