2

Using python script editor in QGIS, I'm trying to create code that extracts features by the location of an input layer for each feature in the intersect layer. The diagram below explains what I mean

enter image description here

My code below iterates over the features in the intersect layer and runs extract by location each time, but everything that touches any feature in the intersect layer is included in each output.

input_shp = QgsProject.instance().mapLayersByName('shp_1')[0]

intersect_shp = QgsProject.instance().mapLayersByName('shp_2')[0]

features = intersect_shp.getFeatures()

for feature in features:
    intersect = processing.run("native:extractbylocation", {'INPUT': input_shp,'PREDICATE':[6],\
    'INTERSECT': intersect_shp, 'OUTPUT':QgsProcessing.TEMPORARY_OUTPUT})['OUTPUT']
    QgsProject.instance().addMapLayer(intersect)
1
  • Intersect everything once then extract by attributes, probably alot faster
    – BERA
    Jul 5, 2021 at 8:23

1 Answer 1

5

Try the following. You need to iteratively select each feature in your intersect layer and run the algorithm on selected features only.

input_shp = QgsProject.instance().mapLayersByName('shp_1')[0]
intersect_shp = QgsProject.instance().mapLayersByName('shp_2')[0]

for feature in intersect_shp.getFeatures():
    intersect_shp.selectByIds([feature.id()])
    processing.runAndLoadResults("native:extractbylocation",
    {'INPUT':input_shp,
    'PREDICATE':[6],
    'INTERSECT':QgsProcessingFeatureSourceDefinition(intersect_shp.id(),
    selectedFeaturesOnly=True,
    featureLimit=-1,
    geometryCheck=QgsFeatureRequest.GeometryAbortOnInvalid),
    'OUTPUT':'TEMPORARY_OUTPUT'})

intersect_shp.selectByIds([])

Your Answer

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

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