Openlayers 3 : update layers of vectors with WFS-T protocol

I want to write this article to help people who wants to make some modifications on a layer easily. You can find lots of tutorial on the web to draw on a layer. This article is focused on how to make modification and how to report these on the web server.

First, i deployed a Geoserver 2.7 in a Tomcat. By default, Geoserver can communicate by WFS.  Tomcat is set on port 8888 on my localhost, that is why i use this port in my code.

All this code are compatible with the latest version of OpenLayers 3 v3.8.2 !

WFS (Web Feature Service) – T (For transactional part)

The Open Source Geospatial Foundation (OSGeo), is a non-profit non-governmental organization whose mission is to support and promote the collaborative development of open geospatial technologies and data. The foundation was formed in February 2006 to provide financial, organizational and legal support to the broader Free and open source geospatial community. It also serves as an independent legal entity to which community members can contribute code, funding and other resources, secure in the knowledge that their contributions will be maintained for public benefit.

OSGeo draws governance inspiration from several aspects of the Apache Foundation, including a membership composed of individuals drawn from foundation projects who are selected for membership status based on their active contribution to foundation projects and governance.

The foundation pursues goals beyond software development, such as promoting more open access to government produced geospatial data and completely free geodata, such as that created and maintained by the OpenStreetMap project. Education and training are also addressed. Various committees within the foundation work on implementing strategies.

https://en.wikipedia.org/wiki/Open_Source_Geospatial_Foundation

Declaring a map and adding a base layer

HTML:

Adding a map element and two buttons (one to delete and the other to save this layer by WFS-T protocol).

<div id="map" class="map"></div>
<div id="customControl"></div>

JavaScript:
Setting the map element.

var map = new ol.Map({
    target: 'map',
    renderer: 'canvas',
    view: new ol.View({
    projection: 'EPSG:3857',
        center: ol.proj.transform([-103.86, 44.49], 'EPSG:4326', 'EPSG:3857'),
        zoom: 10
    })
});

Adding a base layer map. It is more easy to work.

var baseLayerMap = new ol.layer.Tile({
    title: "Global Imagery",
    source: new ol.source.TileWMS({
        url: 'http://localhost:8888/geoserver/nurc/wms',
        params: {LAYERS: 'nurc:Img_Sample', VERSION: '1.1.0'}
    }),
});

map.addLayer(baseLayerMap);

Adding the vector layer by WFS on the map

JavaScript:

var vectorSource = new ol.source.Vector({
    loader: function (extent, resolution, projection) {
        var url = "http://localhost:8888/geoserver/wfs?service=WFS"
            + "&version=2.0.0&request=GetFeature"
            + '&outputFormat=text/javascript'
            + "&typename=sf:streams"
            + "&format_options=callback:loadFeatures"
            + '&srsname=EPSG:3857';

        // use jsonp: false to prevent jQuery from adding the "callback"
        $.ajax({url: url, dataType: 'jsonp', jsonp: false});
    }
});

/**
* JSONP WFS callback function.
* @param {Object} response The response object.
*/
window.loadFeatures = function (response) {
    vectorSource.addFeatures(new ol.format.GeoJSON().readFeatures(response));
};

var vector = new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 255, 1.0)',
            width: 2
        })
    })
});

map.addLayer(vector);

Note: you can see here, we have used a callback function. The callback function are really populars in JavaScript and in OpenLayers API.
 

Adding default control : select, modify

Now, we want to select some points, and modify their positions.

JavaScript:

var selectFeat = new ol.interaction.Select();

map.addInteraction(selectFeat);

var selectedFeat = selectFeat.getFeatures();

var modifyFeat = new ol.interaction.Modify({
    features: selectedFeat
});

map.addInteraction(modifyFeat);

Custom delete function

In Openlayers 3, we do not have yet a delete control. So here is my custom code :

function deleteFeatures() {
    if (selectedFeat.getLength() > 0) {
        var toDeleteFeat = selectFeat.getFeatures().getArray()[0];
        vectorSource.removeFeature(toDeleteFeat);
        selectFeat.getFeatures().remove(toDeleteFeat);
    }
    else
        window.alert("Please select a layer first :" + selectedFeat.getLength());
}

$('#customControlDelete').on('click', function () {
    deleteFeatures();
});

JavaScript:

Custom transactional function

And here is the most important part to make transaction, by WFS protocol, possible.

var transactWFS = function (p, f) {
    switch (p) {
        case 'insert':
            node = formatWFS.writeTransaction([f], null, null, formatGML);
            break;
        case 'update':
            node = formatWFS.writeTransaction(null, [f], null, formatGML);
            break;
        case 'delete':
            node = formatWFS.writeTransaction(null, null, [f], formatGML);
            break;
    }

    s = new XMLSerializer();

    str = s.serializeToString(node);

    $.ajax('http://localhost:8888/geoserver/wfs', {
        type: 'POST',
        dataType: 'xml',
        processData: false,
        contentType: 'text/xml',
        data: str
    }).done();
}

selectFeat.getFeatures().on('change:length', function (e) {
    transactWFS('delete', e.target.item(0));
});

And the job is done ! I hope this little tutorial/try will help you to use the WFS-T protocol in OpenLayers 3.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s