0

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.

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

2 Answers 2

3

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
1

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() 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.