3

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.

1 Answer 1

5

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() )
2
  • Thanks, it seems to be what I was looking for.However I'm not mush of a programmer and I am struggling some what to get this to work. If you have an example that will be great, but thanks again for the help.
    – Jcstay
    Commented Jul 19, 2013 at 10:31
  • I added a minimal example. I need to know more about your setup to be able to extend it, so if you have specific questions, the example can be extended. E.g. based on your problem you could also get the reference to the vectorlayer (simly called vl in the example) in a different way. Also I'm not sure about the "switch off" part. I assume it's about visibility, but you mention it at a place where you said before it's already invisible... Commented Jul 19, 2013 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.