21

I just manually (and somewhat inaccurately I'm sure) retrieved the bounding box coordinates for a county polygon, which is a selection from a larger layer of county shapes. I'd like to be able to use a QGIS plugin or other function to calculate this quickly and not-by-hand. This is almost certainly possible but I couldn't find anything with a Google search

6 Answers 6

29

The following little Python function will output the bounding box coordinates of the currently active feature:

def printBB():
    feature = iface.activeLayer().selectedFeatures()[0]
    print feature.geometry().boundingBox().toString()

To define the function, open the Python console from the Plugins menu, copy and paste the three lines into the console, and press enter. Then you can call the function by typing printBB() and pressing enter while the desired feature is selected.

Edit: For newer Python versions (Python 3.x) use this (print() with brackets):

def printBB():
    feature = iface.activeLayer().selectedFeatures()[0]
    print(feature.geometry().boundingBox().toString())
5
  • 1
    I get this error when I try to run this script: File "<input>", line 4 printBB() ^ SyntaxError: invalid syntax
    – cbunn
    Commented Aug 4, 2015 at 22:01
  • @cbunn make sure you have the layer selected in the layers / table of contents - it's very sensitive to this! Commented Sep 21, 2015 at 18:56
  • thanks for the help. I was also forgetting to press enter to fully define the function printBB() before calling it.
    – cbunn
    Commented Sep 22, 2015 at 20:18
  • 4
    I had to use print(feature.geometry().boundingBox().toString()) for line 3.
    – cm1
    Commented Jun 25, 2018 at 16:08
  • I got the following error for this: Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.3\apps\Python39\lib\code.py", line 63, in runsource code = self.compile(source, filename, symbol) And many others.
    – enor
    Commented Feb 22, 2023 at 7:05
20

QGIS can do it via Polygon from Layer Extent

Vector - Research tools - Polygon From Layer Extent

Will produce a new shapefile with attributes like XMIN XMAX YMIN YMAX AREA WIDTH HEIGHT

3
  • 1
    You have to check Use only selected obects and calculate for every object to get the desired result.
    – AndreJ
    Commented Dec 3, 2013 at 5:12
  • hmm that didn't work for me, the outputted shapefile was blank essentially Commented Dec 3, 2013 at 19:24
  • 1
    You only want to check 'Use only selected objects' if you have objects selected. I left both those fields unchecked and achieved a fine result.
    – Johanna
    Commented Mar 8, 2016 at 10:03
6

If you need many polygon's bounding boxes, on the left hand side,

  • Right click on your layer
  • Click "Export"
  • Click "Save Feature As"

The in the dialog that pops up,

  • Set "Format" to "GeoJSON"
  • Under the "Layer Options" set WRITE_BBOX to YES

Now when you export look inside the file for "bbox" (should be before the feature declaration), like this:

..., "bbox": [ -70.062408006999874, 12.417669989000046, -69.876820441999939, 12.632147528000104 ], "geometry": ...
1
  • 1
    I found a special case bug with export - when your feature crosses the "prime antimeridian" (180 deg longitude), the bounding box values seem wrong. It seems the bounding box coordinates are the max and min coordinates over all the vertices. If the polygon crosses the antimeridian, the min longitude will be close to -180 and the max longitude close to 180. But the most eastward and westward vertices will be different from the min and max longitudes. I believe this represents a bug, but I will need to research further. I encountered this problem working with the U.S. state of Alaska.
    – sb4
    Commented Apr 16, 2021 at 14:55
4

You can also do this using PyShp plugin in Python.. Its a lot simpler...

import shapefile

sf = shapefile.Reader("Path to shapefile...") 
shapes = sf.shapes() 
bbox = shapes[0].bbox # Retrieves the bounding box of the first shape

print bbox # Will print the bounding box coordinates

More information on PyShp and other functionalities can be found here.

1

For quick acces, an option is to keep bbox coordinates in the attribute table.

  • Toogle edit mode
  • Launch Field calculator
  • Set create new field, set name (e.g xmin), type (decimal), length, (precision)
  • Expression: x_min( $geometry)
  • You will get a new field in the attribute table with LEFT coordinate.

    Repeat this for RIGHT, BOTTOM, TOP with expressions:

  • x_max($geometry)
  • y_min($geometry)
  • y_max($geometry)
  • Example of the result enter image description here

    You can then set AutoFields plugin to automatically update these fields when feature is changed.

    0

    I had to do this to generate a field I could import as a list elsewhere.

    1. Install QGIS plugin FieldPyculator
    2. Toggle editing of layer
    3. Create new column in attribute table as string e.g. bbox (save edits)
    4. Open FieldPyculator
    5. Set Update Field to bbox
    6. In Field expression type something like:

      bb = $geom.boundingBox().toString()

      bb = bb.replace(' ','')

      bb = bb.replace(':',',')

      value = bb

    7. Run

    8. Turn off editing and save layer

    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.