[Quick Coding Tip] How to get the extent from a vector or raster layer in QGIS using Python

Posts with the [Quick Coding Tip] tag are thought for giving a quick solution to simple PyQGIS tasks.

If you already know How to load a layer in QGIS using Python, you may run the following code:

ext = layer.extent()

for getting the extent of a vector or raster layer. Instead, using this code:

for feature in layer.getFeatures():
    ext = feature.geometry().boundingBox() # this line is the relevant part

you will get the extent of the current feature (it only works for vector layers).

Regardless of the situation, the  ext variable will be a QgsRectangle() object and not, as expected, something more “readable”. For getting the coordinates of the vertices for the current geometry or layer (I know you want it), you may run this code:

xmin = ext.xMinimum()
xmax = ext.xMaximum()
ymin = ext.yMinimum()
ymax = ext.yMaximum()

or, in a more elegant way, you can store them in a tuple:

(xmin, xmax, ymin, ymax) = (ext.xMinimum(), ext.xMaximum(), ext.yMinimum(), ext.yMaximum())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s