[GIS] Getting canvas’ extent coordinates using PyQGIS

extentspyqgis

I'm trying get the extents of the current map canvas. CRS is 22700 BNG.

My code:

canvas = iface.mapCanvas()
print(canvas)

vLayer = iface.activeLayer()
extents = vLayer.extent()

print(extents)

Which returns

qgis._gui.QgsMapCanvas object at 0x1198c6a68

qgis._gui.QgsMapCanvas object at 0x1198c6a68

I'd like to obtain 4 numbers: xMin, xMax, yMin, yMax

Best Answer

You can get the current map canvas' extent by running this line of code in the QGIS Python Console:

iface.mapCanvas().extent().toString()

In case that you want the extent of the active layer (as your code suggests), run this:

iface.activeLayer().extent().toString()

You could also get the individual numbers like this:

e = iface.mapCanvas().extent()
e.xMaximum()
e.yMaximum()
e.xMinimum()
e.yMinimum()