sábado, 12 de enero de 2019

Creando buffers rectangulares alrededor de puntos con PyQGIS 3

En un post anterior se consideró el mismo tema con la versión previa de QGIS. No obstante, la portabilidad del código allí propuesto a PyQGIS 3 no resulta muy laboriosa y se incluye a continuación:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
layer = iface.activeLayer()
 
feats = [ feat for feat in layer.getFeatures() ]
 
epsg = layer.crs().postgisSrid()
 
uri = "Polygon?crs=epsg:" + str(epsg) + "&field=id:integer&field=x:real&field=y:real&field=point_id:integer""&index=yes"
 
mem_layer = QgsVectorLayer(uri,
                           'rectangular_buffer',
                           'memory')
 
prov = mem_layer.dataProvider()
 
for i, feat in enumerate(feats):
    point = feat.geometry().asPoint()
    new_feat = QgsFeature()
    new_feat.setAttributes([i, point[0], point[1], feat.id()])
    bbox = feat.geometry().buffer(1000, -1).boundingBox()
    tmp_feat = bbox.asWktPolygon()
    xmin1,ymin1,xmax1,ymax1 = bbox.toRectF().getCoords()
    xmin2,ymin2,xmax2,ymax2 = feat.geometry().buffer(2000, -1).boundingBox().toRectF().getCoords()
    p1 = QgsPointXY(xmin1, ymax2)
    p2 = QgsPointXY(xmax1, ymin2)
    new_ext = QgsRectangle(p1,p2)
    new_tmp_feat = new_ext.asWktPolygon()
    new_feat.setGeometry(QgsGeometry.fromWkt(new_tmp_feat))
    prov.addFeatures([new_feat])
 
QgsProject.instance().addMapLayer(mem_layer)

Después de ejecutado el código anterior en la Python Console de QGIS se puede observar en la imagen siguiente que el resultado es el mismo al obtenido con la versión anterior de QGIS.


La portabilidad fue realizada favorablemente.

No hay comentarios: