# Populating polygon extents to attribute table in QGIS?

Is there a way to calculate the XMIN, YMIN, XMAX and YMAX of a polygon and write it to a field in an attribute table?

The Geometry functions available in the Field Calculator are for points.

I am using 1.8.0 for Windows.

• Which version of QGIS? Are you happy to run the latest dev. – Nathan W Mar 11 '13 at 23:12
• I am using 1.8.0 for Windows. I am willing to give anything a try. – Ryan Garnett Mar 12 '13 at 15:05

The Field Calculator in QGIS now contains functions that will work fine for this.

You can now use:

x_min($geometry), x_max($geometry), y_min($geometry), or y_max($geometry)

1. Open field calculator
2. Select 'Create a new field' or 'Update existing field'
3. Enter or select field name / type
4. Use the appropriate function from above

Given a polygon shapefilename, the following python script should do the job:

layer = QgsVectorLayer(shapefilename,"","ogr")
iter = layer.getFeatures()
layer.startEditing()
for ft in iter:
geom=ft.geometry()
ft.setAttribute('XMAX',geom.boundingBox().xMaximum())
ft.setAttribute('XMIN',geom.boundingBox().xMinimum())
ft.setAttribute('YMAX',geom.boundingBox().yMaximum())
ft.setAttribute('YMIN',geom.boundingBox().yMinimum())
layer.updateFeature(ft)
layer.commitChanges()