[GIS] Obtaining feature extent while iterating using PyQGIS

extentsiterationlooppyqgis

I have a polygon layer upon which i want to create a point layer (regular points) depending on each feature's extent of the polygon layer. So far i have to create a field containing the adequate string:
concat(x_min($geometry),',', x_max($geometry),',', y_min($geometry),',', y_max($geometry)

And then parse that field in a loop:

for feature in layer.getFeatures():
    attrs = feature.attributes()
processing.runalg("qgis:regularpoints",attrs[14],1000,0,False,True,outfile)

Since my approach appears to be rather bulky and inflexible i was wondering whether there are more direct ways to get the extends – something like layer.getFeaturesExt() or layer.getFeaturesBbox()?

Best Answer

Assuming that layer is your polygon layer, you may use this code:

for feature in layer.getFeatures():
    bbox = feature.geometry().boundingBox()
    bbox_extent = '%f,%f,%f,%f' % (bbox.xMinimum(), bbox.xMaximum(), bbox.yMinimum(), bbox.yMaximum())
    processing.runalg("qgis:regularpoints",bbox_extent,1000,0,False,True,outfile)

and you will create a grid of regular points for each feature of your polygon layer (without the needing of preliminarily creating a field that stores the coordinates).

Related Question