Web Feature Service - Accessing region countours saved on a GeoServer

In this example, we’re going to look at some layers that are currently accessible on our instance of GeoServer. With WFS, we can see what is available, collect the layers we want by using a query, download the results in geoJSON, and visualize them using geopandas.

We begin by loading the libraries needed for parsing and downloading from WFS and for opening and visualizing the results

%matplotlib inline

# Import WFS from owslib
from owslib.wfs import WebFeatureService

import geopandas as gpd

We start by making a connection to the PAVICS instance we have locally on our server, Boreas. Using WFS, we can very quickly see the contents, which are the layers and the workspaces they’re located with (ie: TravisTest, scratchTJS). These layer names act as dictionaries for


wfs_url = 'http://boreas.ouranos.ca/geoserver/wfs'

# Connect to GeoServer WFS service.
wfs = WebFeatureService(wfs_url, version='2.0.0')

# Print the list of available layers

More information about each layer is stored in the contents dictionary.

sorted_layer_ids = list(sorted(wfs.contents.keys()))
canada_admin_boundaries_index = sorted_layer_ids.index('public:canada_admin_boundaries')

for layerID in sorted_layer_ids[canada_admin_boundaries_index - 1:canada_admin_boundaries_index + 2]:
    layer = wfs[layerID]
    print('Layer ID:', layerID)
    print('Title:', layer.title)
    print('Boundaries:', layer.boundingBoxWGS84, '\n')
Layer ID: public:USGS_HydroBASINS_lake_na_lev12
Title: USGS_HydroBASINS_lake_na_lev12
Boundaries: (-180.0, -90.0, 180.0, 90.0)

Layer ID: public:canada_admin_boundaries
Title: Canada Administrative Boundaries
Boundaries: (-141.01807315799994, 41.681435425000075, -52.61940850399992, 83.13550252400006)

Layer ID: public:global_admin_boundaries
Title: Global Admin Boundaries
Boundaries: (-180.0, -89.99892578124998, 180.00000000000003, 83.59960937500006)

We can then perform a GetFeatures call using the layer name as a target. This returns an IOstream that can be written as a geoJSON file, a common file format for vector data served throughout the web. To reduce the download size, we’ll only fetch the features (here polygons), intersecting a small region defined by a bounding box.

layer_id = 'public:canada_admin_boundaries'
meta = wfs.contents[layer_id]

# Get the actual data
data = wfs.getfeature(typename='public:canada_admin_boundaries', bbox=(-74.5, 45.2, -73, 46), outputFormat='JSON')

# Write to file
fn = 'output.geojson'
with open(fn, 'wb') as fh:
Canada Administrative Boundaries

Once the geoJSON file is downloaded, we can either open it with a GIS application or we can read the features using geopandas.

layers = gpd.read_file(fn)
<matplotlib.axes._subplots.AxesSubplot at 0x7f439b4252d0>
[ ]: