I'm trying to zoom to a layer that was loaded with a script, just like manually would be done by right clicking the layer and pressing the "Zoom to Layer" button.

I've tried several ways and the closest I got was using canvas but it wouldn't zoom in but instead it would open a secondary screen with the layer extended.

up vote 2 down vote accepted

In iface (PyQGIS 3) there are 12 methods that involve "Zoom":

zoomFull, zoomToActiveLayer, zoomToNext, zoomToPrevious, actionZoomActualSize, actionZoomFullExtent, actionZoomIn, actionZoomLast, actionZoomNext, actionZoomOut, actionZoomToLayer, actionZoomToSelected

and in QgsMapCanvas other 13 additional methods:

zoomByFactor, zoomIn, zoomLastStatusChanged, zoomNextStatusChanged, zoomOut, zoomScale, zoomToFeatureExtent, zoomToFeatureIds, zoomToFullExtent, zoomToNextExtent, zoomToPreviousExtent, zoomToSelected, zoomWithCenter

When I use, e.g. 'zoomToActiveLayer' iface method at Python Console, for polygon1 as Active Layer (see following image):

zoomToActiveLayer

enter image description here

I got result of following image.

enter image description here

You can try out whatever of above methods (use 'help' for command syntax if it is necessary).

  • Thank you, your answer is correct, and I kinda got it to work at least setting the layer to active. For some reason it is not throwing any errors but I had to call iface.zoomToActiveLayer() in console since it appears to ignore that line from my code. Any ideas why is it doing so? – Thriskel Nov 8 at 20:50

This is what i do in a plugin to view a newly added layer.

layer = QgsVectorLayer(path, layerName, 'ogr')
ex    = layer.extent()

# Add a small space/border on each side of the layer
hborder = ex.height() / 100
wborder = ex.width() / 100
ex.set(ex.xMinimum() - wborder, 
       ex.yMinimum() - hborder, 
       ex.xMaximum() + wborder, 
       ex.yMaximum() + hborder
)

# Find out if we need to transform coordinates
proj = QgsProject.instance()
if layer.crs().authid() != proj.crs().authid():
    print("Layer has not the same CRS as proj", 
          layer.crs().authid(), 
          proj.crs().authid()
    )
    tr = QgsCoordinateTransform(layer.crs(), proj.crs(), proj)
    ex = tr.transform(ex)

iface.mapCanvas().setExtent(ex)
iface.mapCanvas().refresh()

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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