What I am trying to do: loop through a point shapefile and select each point that falls into a polygon.
The following code is inspired by a spatial query example I found in a book:
mitte_path = r"D:\PythonTesting\SelectByLocation\mitte.shp" punkte_path = r"D:\PythonTesting\SelectByLocation\punkte.shp" polygon = QgsVectorLayer(mitte_path, 'Mitte', 'ogr') points = QgsVectorLayer(punkte_path, 'Berlin Punkte', 'ogr') QgsMapLayerRegistry.instance().addMapLayer(polygon) QgsMapLayerRegistry.instance().addMapLayer(points) polyFeatures = polygon.getFeatures() pointsCount = 0 for poly_feat in polyFeatures: polyGeom = poly_feat.geometry() pointFeatures = points.getFeatures(QgsFeatureRequest().setFilterRect(polyGeom.boundingBox())) for point_feat in pointFeatures: points.select(point_feat.id()) pointsCount += 1 print 'Total:',pointsCount
This works, and it does select datasets, but the problem is that it selects by bounding box, hence obviously returning points I am not interested in:
How could I go about only returning points within the polygon without using qgis:selectbylocation?
I have tried using the within() and intersects() methods, but as I was not getting them to work, I resorted to the code above. But perhaps they're the key after all.