OpenLayers 3.16 - Three flavours of Geoserver WFS as ol.layer.Vector

Today I want to recap on the different ways of adding a vector layer from a Geoserver WFS. I used OL 3.5 when I published this post in May 2015. Since then I have switched to OL 3.16 and decided to update this post rather than to write a new post. There is really no reason not to be working with the latest version of OpenLayers. If you are familiar with WFS vector sources in OpenLayers 3.x or if you used my previous code snippets then please review the update notes. There have been a few significant changes between OL 3.5 and OL 3.16.

The examples are based on the vector-wfs example from the OpenLayers page.

We create a vector layer with a WFS source like so:

We use a bbox loading strategy and use the extent in the loader function for the WFS source.

By default the WFS request will return XML from Geoserver. Inside the .done() function we define WFS format object which will be used to read the features from the WFS response and add these to the source.

Here is a working JSFiddle for this code.

As an alternative to the WFS format we can directly request GeoJSON from GeoServer. GeoJSON will be more compact and easier to parse.

We define the outputFormat as ‘application/json’ inside the AJAX call.

In order to read the features from the GeoJSON response we use a GeoJSON format object inside the .done() function.

Here is a working JSFiddle.

An alternative to the JSON format is the JSONP format which allows us to receive data from Geoserver without changing the CORS access on the webserver. JSONP is by default disabled and must be enabled in Geoserver.

The AJAX call must configured as shown below for the callback with padded JSON.

We set the output format in the AJAX call to be ‘text/javascript’. We don’t use a .done() function on the AJAX call but define dataType, jsonp, and jsonCallback parameter. The response from the WFS call will be sent to the jsonCallback function. Inside the load features function we use again a GeoJSON format object to read features from the response and add these to the source of the WFS layer.

Here is a working JSFiddle.

If you have problems loading data I recommend to use the Chrome developer tools (F12). A common error is the use of a http source on a https page.

Filter for XHR on the network tab of the debug tools to inspect the details of your WFS calls.

Please drop me a comment if this helped you, if you have questions or if you can recommend further improvements to these examples.

Next time… WFS-T.

This is an older article from my blog which I posted in 2015 and then updated for OpenLayers 3.16 in 2016.