[GIS] How to get the extent of a group of Raster layers and zoom to it with PyQGIS

pyqgisqgisqgis-plugins

I want to find a way to zoom to a group within the QgsLayerTreeView. The group only contains QgsRasterLayer. The indirect approach would be to create a QgsRectangle and serve it to the QgsMapCanvas.setExtent() method.

Unfortunately I don't see a way to obtain the extent of a QgsRasterLayer, kind of Bounding Box or "geometry", which I need for the creation of such a rectangle.

Best Answer

Your idea was actually fine. Raster layers' extent can be accessed via the extent() method. However, you would need to combine your rasters' extents before zooming in.

Assuming your raster layers and the map are in the same reference system (i.e., no on-the-fly projection), you can zoom in to the extent of a desired group copying this code snippet to your QGIS Python console:

extent = QgsRectangle()
extent.setMinimal()

# Iterate through layers from certain group and combine their extent
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("rasters") # Adjust this to fit your group's name
for child in group.children():
    if isinstance(child, QgsLayerTreeLayer):
        extent.combineExtentWith( child.layer().extent() )

iface.mapCanvas().setExtent( extent )
iface.mapCanvas().refresh()

Please tell me if you face any trouble with it.

Note: The solution above should work for both raster and vector layers.