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[0].x()
    xmin = vertices[0].x()
    ymax = vertices[0].y()
    ymin = vertices[0].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()


    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[0].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?

  • 1
    possible duplicated gis.stackexchange.com/q/79248/49538
    – Fran Raga
    Nov 22, 2019 at 19:09
  • 1
    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()"
    – Elio Diaz
    Nov 22, 2019 at 19:35

1 Answer 1


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()
    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)
    – xlDias
    Nov 25, 2019 at 18:14

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.