QGIS Select 与 python 相交的多边形

QGIS Select polygons which intersect points with python

我刚开始使用 QGIS,我有一个点 shapefile 和一个多边形 shapefile。我想 select 所有至少有一个点的多边形。我 运行 遇到的问题是这需要多长时间。我有 100 万个点和大约 320,000 个多边形,因此使用空间查询需要很长时间。我听说我需要编写一个带有空间索引的 python 脚本才能获得可行的快速结果,但我不知道如何处理这个问题。任何帮助将不胜感激。

我试图从其他堆栈溢出问题中拼凑出来的是:

pointProvider = self.pointLayer.dataProvider()
all_point = pointProvider.getFeatures()
delta = 0.1

for point in all_point:

    searchRectangle = QgsRectangle(point.x() - delta, point.y()  - delta, point.x() + delta, point.y() + delta)

    candidateIDs = line_index.intesects(searchRectangle)

    for candidateID in candidateIDs:
        candFeature == rotateProvider.getFeatures(QgsFeatureRequest(candidateID)).next()
        if candFeature.geometry().contains(point):

            break

这会抛出一个 NameError: name 'self' is not defined

我在 GIS Stack Exchange 上找到了答案,您可以在其中找到 here

我使用的代码是:

from qgis.core import *
import processing

layer1 = processing.getObject('MyPointsLayer')
layer2 = processing.getObject('MyPolygonsLayer')

index = QgsSpatialIndex() # Spatial index
for ft in layer1.getFeatures():
    index.insertFeature(ft)

selection = [] # This list stores the features which contains at least one point
for feat in layer2.getFeatures():
    inGeom = feat.geometry()
    idsList = index.intersects(inGeom.boundingBox())
    if idsList:
        selection.append(feat)

# Select all the polygon features which contains at least one point
layer2.setSelectedFeatures([k.id() for k in selection])