8

How do I select all features in a polygon layer that intersect (overlap) a line feature?

I need to implement this in python using QGIS, thus pyqgis. This code illustrates what I am looking for (line 10 is sort of pseudo-code, i.e. what I am looking for):

 1 area_layer_file = "./Areas.shp"
 2 line_layer_file = "./Lines.shp"
 3 
 4 area_layer = QgsVectorLayer(area_layer_file, "Areas", "ogr")
 5 line_layer = QgsVectorLayer(line_layer_file, "Lines", "ogr")
 6 
 7 areas = []
 8 for line_feature in line_layer.getFeatures():
 9     request = QgsFeatureRequest(QgsExpression(
10             area_feature.geometry().intersects(line_feature.geometry())
11         ))
12     areas = [area for area in area_layer.getFeatures(request)]

This image illustrates my question: the red line intersects the yellow selected areas.

enter image description here

1

2 Answers 2

11
areas = []
for line_feature in line_layer.getFeatures():
    cands = area_layer.getFeatures(QgsFeatureRequest().setFilterRect(line_feature.geometry().boundingBox()))
    for area_feature in cands:
        if line_feature.geometry().intersects(area_feature.geometry()):
            areas.append(area_feature.id())

area_layer.select(areas)
3

QGIS 3 you can do as the answer above, but without the QgsFeatureRequest().

areas = []
for line_feature in line_layer.getFeatures():
    for area_feature in area_layer.getFeatures():
        if line_feature.geometry().intersects(area_feature.geometry()):
            areas.append(area_feature.id())

area_layer.select(areas)

Your Answer

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