QGIS WFS Filter – Adding Spatial Filter to WFS Layer Request Not Working in QGIS

filtergetfeatureqgiswfs

I'm trying to load big WFS layers to my project by mean of a Python script but since I only need to display features located in the south west of France I thought I could easily add a bbox filter in the request url like this:

https://wxs.ign.fr/administratif/geoportail/wfs?VERSION=2.0.0&TYPENAMES=ADMINEXPRESS-COG-CARTO.LATEST:arrondissement&COUNT=1000&SRSNAME=EPSG::4326&BBOX=42.374778,-2.109375,47.115000,2.856445&request=GetFeature&

However, despite the bbox filter, the WFS layer is loaded nationwide every time I add it to the QGIS project.

How should I proceed to load only the features I want ?

I already had a look there:

Best Answer

You can use the SQL Query Composer in the WFS Server Connection Dialog when adding the data. There you can create a spatial filter. enter image description here

EDIT: For using WFS via GeoServer in python and setting a bounding-box GeoServer requires a POST rather than a GET request as statet here:

https://docs.geoserver.org/latest/en/user/services/wfs/reference.html

"While there are limited options available in a GET request for spatial queries (more are available in POST requests using filters), filtering by bounding box (BBOX) is supported."

So one approach would be to query the data in your script beforehand making a post request and from the result create the layer on the fly:

That's how your query would look like in curl:

curl --location --request POST 'https://wxs.ign.fr/administratif/geoportail/wfs?VERSION=2.0.0&TYPENAMES=ADMINEXPRESS-COG-CARTO.LATEST:arrondissement&COUNT=1000&SRSNAME=EPSG:4326&BBOX=47.0,2.7,47.1,2.8&request=GetFeature&outputFormat=json'

In QGIS you could load the data using urllib like:

from urllib import request, parse
import json

# Query Data
url = 'https://wxs.ign.fr/administratif/geoportail/wfs?VERSION=2.0.0&TYPENAMES=ADMINEXPRESS-COG-CARTO.LATEST:arrondissement&COUNT=1000&SRSNAME=EPSG:4326&BBOX=47.0,2.7,47.1,2.8&request=GetFeature&outputFormat=json'
req = request.Request(url, method="POST")
r = request.urlopen(req)
content = r.read().decode('utf-8')
print(content)

# Add Layer
vlayer = QgsVectorLayer(content,"Some Data","ogr")
QgsProject.instance().addMapLayer(vlayer)

Note: I changed your initial bounding box in the sample to a smaller value - your initial bounding box result has around 8MB of data.

enter image description here

Related Question