2

I have two layers, "IDN_ALL" as Polygon and "Point_Link" as point. "Point_Link" is the active layer. I want to select point data outside polygon data.

Code:

Layer1 = iface.activeLayer()
Layer2 = ??
layer1.selectByexpression("\"?..")

How can I select points outside polygons?

1 Answer 1

6

Try the options below. This will select all features in your point layer which lie outside of your polygon layer.

Note: Both layers should be in the same Coordinate Reference System, and in both cases make absolutely sure that the layer names match yours and are spelt correctly e.g. 'Point_Link' for the point layer and 'IDN_ALL' for the polygon layer.

Option 1- use processing algorithm 'Select By Location'

project = QgsProject().instance()
Layer1 = project.mapLayersByName('Point_Link')[0]
Layer2 = project.mapLayersByName('IDN_ALL')[0]
processing.run("qgis:selectbylocation", {'INPUT':Layer1,'PREDICATE':[6],'INTERSECT':Layer2,'METHOD':0})
Layer1.invertSelection()

Option 2- This approach avoids the use of processing, but will produce the same result.

project = QgsProject().instance()
Layer1 = project.mapLayersByName('Point_Link')[0]
Layer2 = project.mapLayersByName('IDN_ALL')[0]
index = QgsSpatialIndex(Layer1.getFeatures())
pntFts = [f for f in Layer1.getFeatures()]

pts2select = []
for f in Layer2.getFeatures():
    candidateIds = index.intersects(f.geometry().boundingBox())
    candidateFts = [f for f in pntFts if f.id() in candidateIds]
    for p in candidateFts:
        if p.geometry().within(f.geometry()):
            pts2select.append(p.id())
    
Layer1.selectByIds(pts2select)
Layer1.invertSelection()
9
  • thankyou. I try to run and find this error report Traceback (most recent call last): ltr/./python/plugins\processing\core\Processing.py", line 181, in runAlgorithm raise QgsProcessingException(msg) _core.QgsProcessingException: There were errors executing the algorithm. Commented Sep 24, 2020 at 3:58
  • Double check that the layer names exactly match yours. Also, which version of QGIS do you use?
    – Ben W
    Commented Sep 24, 2020 at 4:14
  • i used QGIS 3.10 Commented Sep 24, 2020 at 4:24
  • @adham CMajid, it works fine for me in both 3.10 and 3.14. I can't say why it doesn't work for you. I have added another option to my answer which does not rely on processing. Please try that instead. If your layers are very large e.g. thousands of features, let me know and I will edit the code.
    – Ben W
    Commented Sep 24, 2020 at 5:06
  • 1
    that's great. running successfully. thankyou Ben Commented Sep 24, 2020 at 6:59

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.