PyQGIS进行空间连接
我在做一个QGIS 2.0/2.2和Python 2.7的插件,想要根据几何函数QgsGeometry.intersects()来更新一个图层的字段属性,用另一个图层的字段属性。我的第一个图层是一个点图层,第二个图层是一个包含方位角测量的矢量折线图层的缓冲区。我想把点图层更新为包含它与之相交的缓冲区多边形的方位角信息(这基本上是一个空间连接)。这个过程是为了自动化在这里描述的操作。目前,我的点图层的方位字段在提交更改后只更新了第一个特征(我本来期待所有特征都能更新)。
rotateBUFF = my buffer polygon layer
pointLayer = my point layer to obtain azimuth data
rotate_IDX = rotateBUFF.fieldNameIndex('bearing')
point_IDX = pointLayer.fieldNameIndex('bearing')
rotate_pr = rotateBUFF.dataProvider()
point_pr = pointLayer.dataProvider()
rotate_caps = rotate_pr.capabilities()
point_caps = point_pr.capabilities()
pointFeatures = pointLayer.getFeatures()
rotateFeatures = rotateBUFF.getFeatures()
for rotatefeat in rotateFeatures:
for pointfeat in pointFeatures:
if pointfeat.geometry().intersects(rotatefeat.geometry()) == True:
pointID = pointfeat.id()
if point_caps & QgsVectorDataProvider.ChangeAttributeValues:
bearing = rotatefeat.attributes()[rotate_IDX]
attrs = {point_IDX : bearing}
point_pr.changeAttributesValues({pointID : attrs})
1 个回答
1
把迭代器放到循环里就能解决问题:
for rotatefeat in rotateBUFF.getFeatures():
for pointfeat in pointLayer.getFeatures():
另外,如果你在数据提供者上工作,就不需要提交更改。有两种方法可以编辑数据:
- 在图层上使用它的 编辑缓冲区,但你必须先开启编辑模式。一旦编辑完成,就必须提交更改。
- 在数据提供者上按需编辑。无需提交更改,使用changeAttributeValues时更改会直接生效。
通常建议在图层上编辑,以防止在未开启编辑模式的图层上进行修改。这对于插件尤其重要。不过,如果这段代码只是给你自己用,使用数据提供者可能会更简单。编辑缓冲区的一个好处是你可以一次性提交所有更改,如果在循环中出现问题,可以放弃这些更改。