JSON with GeoServer and Leaflet

Just before the Christmas break I was working on a project with Leaflet and GeoServer and had the need to consume vector data from GeoServer in Leaflet. Leaflet doesn’t directly support WFS services on their own, but it will happily work with JSON data, fortunately GeoServer can output a WFS service as JSON without too many problems.

To avoid any nasty cross domain issues, the first step is to turn on JSONP support in GeoServer, to do this open the web.xml file in the ../geoserver/WEB-INF/ folder of your GeoServer deployment and add this statement at the bottom of the file

<context-param>
    <param-name>ENABLE_JSONP</param-name>
    <param-value>true</param-value>
</context-param>

 

Once you have done this, restart GeoServer and do a get capabilities request and you should see JSONP appear in your list of result formats

getCapabilities

GeoServer is now ready to receive JSONP requests, so the next step is to start requesting data with Leaflet. There is a existing plugin for JSONP ajax requests, but it is pretty straight forward to roll your own using JQuery.

Create the GeoServer JSONP request, GeoServer uses a slightly weird syntax for this so you need to include the callback in the URL:

var geoJsonUrl = “http://000.000.0.000:8080/geoserver/cite/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cite:BoreHoles&outputFormat=text/javascript&format_options=callback:processJSON”;

Send the request with jQuery

$.ajax(geoJsonUrl,
{ dataType: “jsonp” }
).done(function ( data ) {
});

Create the callback function to turn the json into a vector Leaflet layer

function processJSON(data) {
boreHoles = data;

    boreHolePoints = L.geoJson(boreHoles,{
onEachFeature: onEachFeature,
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {
icon: getIcon(feature.properties.type,’unhighlight’)
});
}
}).addTo(map);
}

All done You should now have a new json layer added to your map, which will look something like this

csiro

You can see this GeoServer, Leaflet, JSON combo in action on a site we built that has just gone live for CSIRO

http://www.groundwatercooling.csiro.au/feed.html

Email me directly here or find me on Twitter

Andrew

Comments are closed.