1

I'm trying to add the intersected geometries of 2 layers in a pyqgis code.

I have a grid made up by cells (so a polygon) 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.

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())
  • 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 '16 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 '16 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 '16 at 13:40
  • Thanks for sharing, that is interesting...I have noted down your solution for sure ;) – Joseph Nov 11 '16 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 '16 at 13:46

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.