为QGIS 2空间连接(PyQGIS)创建空间索引

2024-10-03 17:16:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一些代码来在QGIS 2和2.2中做一个简单的空间连接(位于缓冲区内的点获取缓冲区的属性)。不过,我想使用一个QgsSpatialIndex来加快速度。从这里我可以去哪里:

pointProvider = self.pointLayer.dataProvider()
rotateProvider = self.rotateBUFF.dataProvider()

all_point = pointProvider.getFeatures()
point_spIndex = QgsSpatialIndex()
for feat in all_point:
    point_spIndex.insertFeature(feat)

all_line = rotateProvider.getFeatures()
line_spIndex = QgsSpatialIndex()
for feat in all_line:
    line_spIndex.insertFeature(feat)

rotate_IDX = self.rotateBUFF.fieldNameIndex('bearing')
point_IDX = self.pointLayer.fieldNameIndex('bearing')

self.pointLayer.startEditing()
for rotatefeat in self.rotateBUFF.getFeatures():
    for pointfeat in self.pointLayer.getFeatures():
        if pointfeat.geometry().intersects(rotatefeat.geometry()) == True:
            pointID = pointfeat.id()
bearing = rotatefeat.attributes()[rotate_IDX]
self.pointLayer.changeAttributeValue(pointID, point_IDX, bearing)
self.pointLayer.commitChanges()

Tags: inselfforlineallpointfeatidx
1条回答
网友
1楼 · 发布于 2024-10-03 17:16:35

要进行这种空间连接,可以使用QgsSpatialIndex(http://www.qgis.org/api/classQgsSpatialIndex.html)intersects(QgsRectangle)函数来获取候选特征ID的列表,或者使用nearest neighbor(QgsPoint,n)函数获取n个最近邻居的列表作为featureid。在

由于只需要缓冲区内的点,所以intersects函数似乎最适合。我没有测试是否可以使用退化的bbox(点)。如果没有,就在你的点周围做一个很小的边界框。在

intersects函数返回具有与给定矩形相交的边界框的所有要素,因此您必须测试这些候选要素是否具有真正的交集。在

外部循环应该在这些点上(您希望从包含它们的缓冲区向每个点添加属性值)。在

# If degenerate rectangles are allowed, delta could be 0,
# if not, choose a suitable, small value
delta = 0.1
# Loop through the points
for point in all_point:
    # Create a search rectangle
    # Assuming that all_point consist of QgsPoint
    searchRectangle = QgsRectangle(point.x() - delta, point.y()  - delta, point.x() + delta, point.y() + delta)
    # Use the search rectangle to get candidate buffers from the buffer index
    candidateIDs = line_index.intesects(searchRectangle)
    # Loop through the candidate buffers to find the first one that contains the point
    for candidateID in candidateIDs:
        candFeature == rotateProvider.getFeatures(QgsFeatureRequest(candidateID)).next()
        if candFeature.geometry().contains(point):
            # Do something useful with the point - buffer pair

            # No need to look further, so break
            break

相关问题 更多 >