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()
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[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?
Best Answer
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()