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

时间:2014-05-14 17:25:29

标签: python qgis

我已经编写了一些代码来在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()

1 个答案:

答案 0 :(得分:1)

要执行此类空间连接,您可以使用QgsSpatialIndex(http://www.qgis.org/api/classQgsSpatialIndex.html)交叉(QgsRectangle)函数来获取候选featureID列表或nearestNeighbor(QgsPoint,n)函数以获取列表n最近邻居作为featureID。

由于您只想要位于缓冲区内的点,因此交叉函数似乎最合适。我还没有测试是否可以使用退化的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