2

I'm trying to use PyQgis to query a WFS-service and return the items found within a certain bounding box.

When entering the following uri in the browser, it returns a xml with a limited set of results

uri = 'https://geoservices.informatievlaanderen.be/overdrachtdiensten/GRB/wfs?request=getFeature&srsname=EPSG:31370&typename=GRB:ADP&BBOX=183918,186419,184189,186632,EPSG:31370'

Using PyQgis I wish to load this into QGIS (3.4.3):

layer = QgsVectorLayer(uri, "WFS_Layer", "WFS")
print(layer.isValid())
project = QgsProject.instance()
project.addMapLayer(layer)

The layer which loads, loads all the data within my view extent, not just the data I requested in BBOX. Afterwards I need to get some attributes of the loaded data, therefor I wish to limit the amount of data, as loading times easily get too high.

Is this a bug or am I doing something wrong?

EDIT:

Reading the link below, I think it's a chosen behaviour in the Qgis implementation. Is there any way to circumvent this? https://issues.qgis.org/issues/8871

I also tried the solution provided in the question below, but had no luck. Why doesn't QGIS show the results from a WFS BBOX from a Python script

1

It seems that this default behaviour cannot be overwritten. So to solve my problem, I finally decided to just download the files locally through WFS and load these.

The code is given below, in capital what to change to your own values (+ change epsg value)

import zipfile
from io import BytesIO  # Python 3

proj_xmin= INTVALUE
proj_xmax= INTVALUE
proj_ymin= INTVALUE
proj_ymax= INTVALUE


print('Beginning file download with urllib2...')

url = 'YOURSERVERURL&BBOX='+str(int(proj_xmin))+','+str(int(proj_ymin))+','+str(int(proj_xmax))+','+str(int(proj_ymax))+',EPSG:31370&outputFormat=shape-zip'
response = urllib.request.urlopen(url)
#filename = response.info()['Content-Disposition'].split('=')[-1]
foldername = 'FOLDERLOCATION'
data = response.read()
try:
    with BytesIO() as zipdata:
        zipdata.write(data)
        myzipfile = zipfile.ZipFile(zipdata)
        myzipfile.extractall(foldername)
        myzipfile.close()
except:
    print('Could not write the files')

# Add vectorlayer to Qgis 3.x
iface.addVectorLayer(foldername+"/SHAPENAME.shp", "", "ogr")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.