# Getting bounding box of polygon

I'm having difficulties to get the bounding box of a polygon. My code is the following:

``````def getBoundingBox(self):
boundingBox = []
polygon = self.getVectorLayer()
vertices = polygon.geometry().asPolygon()

xmax = vertices.x()
xmin = vertices.x()
ymax = vertices.y()
ymin = vertices.y()

for vertice in vertices:
if vertice.x() > xmax:
xmax = vertice.x()
if vertice.x() < xmin:
xmin = vertice.x()
if vertice.y() > ymax:
ymax = vertice.y()
if vertice.y() < ymin:
ymin = vertice.y()

boundingBox.append(xmax)
boundingBox.append(xmin)
boundingBox.append(ymax)
boundingBox.append(ymin)

return boundingBox
``````

The error message I get is

AttributeError: 'QgsVectorLayer' object has no attribute 'geometry'

The function `self.getVectorLayer()` works perfectly fine for other tools I wrote, thus this shouldn't be the problem. With the line `xmax = vertices.x()` I wanted to get the first vertice in the polygon, which probalby doesn't work that way, but it seems the problem starts even earlier.

Any ideas?

• possible duplicated gis.stackexchange.com/q/79248/49538 Nov 22, 2019 at 19:09
• if you check "layer = iface.activeLayer()", then dir(layer) you'll see there's no attribute "geometry", maybe you can use "layer.extent()" which returns the coordinates as well. Maybe you are looking for "layer.getFeature().geometry()" Nov 22, 2019 at 19:35

You're confusing a feature with a vector layer.

A feature is a row on a vector layer that may contain attributes and geometry. A vector layer is a set of features that represent "the same kind of data", like a set of roads.

(Im being really simplistic with this explanation, please look more into it)

Now, assuming that you want the bounding box of all features in a vector layer, select all the features in the vector layer and use the method boundingBoxOfSelected()

``````def getBoundingBox(self):
layer = self.getVectorLayer()
layer.selectAll()
return layer.boundingBoxOfSelected()
``````
• this looks super useful. Thank you for that. Just one more question to make sure I got it right. If I wright in another function something like bbox = self.getBoundingBox() and then I want the xMax value of my bounding box I can acces it with bbox.xMax because bbox is an object that includes the four double variables xMin, yMin, xMax, yMax. Am I right
– DGIS
Nov 23, 2019 at 16:17
• Almost right, the actual attribute to access would be bbox.xMaximum(). As described in the docs for QgsRectangle (which is the class of the object returned by the boundingBoxOfSelected method) Nov 25, 2019 at 18:14