I want to import a WFS layer from an URL, but spatial filter to import only the objets that intersect or are inside a polygon that i've drawn.

I wrote a code but it doesnt seem to work as intended because the imported layer is empty.

        params = {
    'srsname': 'EPSG:4326',
    'typeName': "RPG.2013:rpg_2013",
    'url': wfs_url,
# Get the polygon layer
polygone_layer = QgsProject.instance().mapLayersByName(polygon_name)[0]

# Get the polygon geometry
####### I've tried multiple things, nothing seemed to work
feature = polygone_layer.getFeature(0)
polygon_geometry = feature.geometry()

# Define the filter based on the polygon geometry
cql_filter = "INTERSECTS(the_geom, {})".format(polygon_geometry.asWkt())

# Add the filter to the WFS request parameters
params['cql_filter'] = cql_filter

# Create a vector layer from the modified WFS request parameters
wfs_couche = QgsVectorLayer('{}?{}'.format(wfs_url, '&'.join(['{}={}'.format(k, v) for k, v in params.items()])), nom_couche, 'WFS')

# Add the layer to the map

After tinkering for days, the best result I could achieve was getting the extent rectangle from the polygon and use it as a filter, however, the layer created contained 0 objects....

enter image description here By the way, the SRS I'm using is the same one required by the WFS API, I've also tried adding and deleting parameters, but it didn't change anything.

  • Your source seems to have GetCapabilities in the server request. Is that normal, shouldn't it be GetFeature? What do you have as source URL with a well working WFS layer?
    – user30184
    Mar 22 at 7:54
  • I did try the get feature, but its still the same issue. The screenshot i shared was just an example
    – emanas
    Mar 22 at 19:52
  • By the way, i changed the image, as you can see even using a "GetFeature" its not working
    – emanas
    Mar 22 at 20:14
  • I would have a try with a polygon that has coordinates flipped. WFS 2.0 expects latitude-longitude order for EPSG:4326.
    – user30184
    Mar 22 at 20:37
  • OMG YOU ARE A LIFE SAVER !!!! THAT WAS THE ISSUE !!! Two last questions tho First one : How can i get a polygon's geometry ? because right now i'm using extend and .getrect (which are for a rectangle). Second question : how can i swap the coordinates latitude-longitude of an object through Pyqgis ?
    – emanas
    Mar 22 at 21:37


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.