[GIS] Referencing layer in table of contents using PyQGIS

layerspyqgispython-2.7

I'm trying to create a plugin for QGIS using python, But need some help. I want to 1.Zoom to a layer and 2. make the layer visible(switch off or on).

But I have managed to zoom to an active layer by setting the active layer in the map canvas by using.

import qgis
canvas = qgis.utils.iface.mapCanvas()
acl = canvas.layer(1)
qgis.utils.iface.setActiveLayer(acl)
> True
qgis.utils.iface.zoomToActiveLayer()

But this only work as long as the layer is viable(obviously since I use canvas). So I need another way to "point" to a layer and then zoom to and switch off.

Best Answer

You can use a combination of QgsMapCanvas.setExtent(), QgsMapLayerRegistry (Use QgsMapLayerRegistry.instance() to get access, since it's a singleton) to find your layer and QgsMapLayer.extent() to get its extent.

canvas = iface.mapCanvas()
vl = QgsMapLayerRegistry.instance().mapLayer( 'YourLayerId' )
canvas.setExtent( vl.extent() )
Related Question