2

I'm trying to add the intersected geometries of 2 layers in PyQGIS.

I have a grid made up by cells (polygons) and a line layer. I want to select the features of the grid layer where they intersect the line features (so basically the Select by Location tool used within a Python script).

The code (that works) is the following:

# get the layers from the interface
grid = iface.activeLayer()
line = iface.activeLayer()

for i in grid.getFeatures():
    for l in line.getFeatures():
        if i.geometry().intersects(l.geometry()):
            print i

It returns (correctly) 17 features.

What I'm not able to to is to add these QgsFeatures as a selection to the grid layer.

1
  • I am a little confused this is working because you use iface.activeLayer() to get both input layers, so they are identical? Therefore, if you have 17 features to test for an intersection, with the same 17 features, you get 17 self-intersections.
    – MrXsquared
    Sep 2, 2021 at 16:05

1 Answer 1

2

Sorry, guys.. I've tried everything but not the easiest solution:

# get the layers from the interface
grid = iface.activeLayer()
line = iface.activeLayer()

for i in grid.getFeatures():
    for l in line.getFeatures():
        if i.geometry().intersects(l.geometry()):
        # add the selection to the layer
            grid.select(i.id())
5
  • Looks like a great solution for a small number of features. You could also use the answer in this post which would be useful for large number of features as it itterates through one layer's features (instead of iterating through both layers as your code does).
    – Joseph
    Nov 11, 2016 at 12:12
  • 1
    @Joseph Thanks! Actually I'm working with a lot of features so, lloping over a single layer is sure better
    – matteo
    Nov 11, 2016 at 13:15
  • @Joseph I made some benchmark of both "my" code and the one you suggested. The polygon has 17.000 features while the line just 3. My code takes less time (not so much but a little bit) compared to the other one. Just for info ;)
    – matteo
    Nov 11, 2016 at 13:40
  • Thanks for sharing, that is interesting...I have noted down your solution for sure ;)
    – Joseph
    Nov 11, 2016 at 13:42
  • Maybe the speed is because I just have 3 feature in the line layer (but the problem in my case is that the polygon layer has always a lot of features). So calculating the bbox as suggested in the other question is time consuming with few features.
    – matteo
    Nov 11, 2016 at 13:46

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.

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