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
The following little Python function will output the bounding box coordinates of the currently active feature:
def printBB(): feature = iface.activeLayer().selectedFeatures() 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() print(feature.geometry().boundingBox().toString())
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.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.
If you need many polygon's bounding boxes, you can "Save As..." your layer to GeoJSON with WRITE_BBOX=YES option and there will be a single "bbox" attribute before your "geometry" attribute, even for multipolygons.
..., "bbox": [ -70.062408006999874, 12.417669989000046, -69.876820441999939, 12.632147528000104 ], "geometry": ...
For quick acces, an option is to keep bbox coordinates in the attribute table.
You will get a new field in the attribute table with LEFT coordinate.
Repeat this for RIGHT, BOTTOM, TOP with expressions:
You can then set AutoFields plugin to automatically update these fields when feature is changed.
I had to do this to generate a field I could import as a list elsewhere.
- Install QGIS plugin FieldPyculator
- Toggle editing of layer
- Create new column in attribute table as string e.g. bbox (save edits)
- Open FieldPyculator
- Set Update Field to bbox
In Field expression type something like:
bb = $geom.boundingBox().toString()
bb = bb.replace(' ','')
bb = bb.replace(':',',')
value = bb
- Turn off editing and save layer