WFS-T with OpenLayers 3.16

This post was originally published for OL 3.5 in June 2015. There is no good reason not to use the latest version of OpenLayers and I am updating the code examples today for OL 3.16.

I am currently using GeoServer 2.8. The data store being a PostGIS 2.1 database.

For my test service I use a very simple table with an ID and geometry only. The geometry is defined as geometry, no type nor projection. It is important that the geometry field is called geometry. Otherwise inserts may create records with empty geometry fields. A constraint must be set on the ID or GeoServer will not be able to insert records into the table.

At the core of the OL javascript snippets is the ol.format.WFS.writeTransaction function which takes 4 input parameter. The first 3 parameter define whether the data should be inserted, updated, or deleted from the data source. The 4th parameter takes the form of ol.format.GML and passes on information about the feature type, namespace, and projection of the data.

The writeTransaction node must be serialised with an XMLSerializer to be used in a WFS-T post.

The three use cases (insert/update/delete) and the AJAX call are shown in the following code snippet.

Inserts are called from the drawend event of the OL interaction. The .clear() function on the WFS source reloads the source after each transaction. This ensure that feature IDs are correct for new features and that deleted features are removed from the view.

The ID of a modified feature is stored and the update transaction is posted once the feature is unselected. In order to successfully post an update transaction the boundedBy property must be stripped from the feature properties. A clone of the feature is used to achieve this.

A complete working example is hosted in this jsFiddle.

This is an older post from my blog which has since been switched off. I am sorry for the comments lost.