How can I adjust the zoom level and recenter in QGIS automatically?

I am using QGIS 3.14 and the Python console (pyQGIS). I will be tracking a line from GPS co-ordinates and I want to be able to adjust the screen and zoom level accordingly. Here is my code:

canvas=iface.mapCanvas() #get a reference of the canvas where maps are displayed

#Drawing Polyline
polyline = QgsRubberBand(canvas, False)  # False = not a polygon
points =[]

polyline.setToGeometry(QgsGeometry.fromPolyline(points), None)
polyline.setColor(QColor(0, 128, 255))

#This is how I am adding points and plotting them. (Just for testing)
polyline.setToGeometry(QgsGeometry.fromPolyline(points), None)
polyline.setToGeometry(QgsGeometry.fromPolyline(points), None)

How can I adjust the screen size and zoomlevel accordingly?

Geographic Information Systems Asked on November 21, 2021

1 Answers

One Answer

In short you set canvas extent to bounding box of geometry. So following your lines of code you do it like this:


It might be good idea to zoom out a bit too like this:

canvas.zoomScale(round((canvas.scale() + canvas.scale()/10)/100)*100)

And sometimes you need to refresh canvas too to make sure you see all fresh:


Answered by Miro on November 21, 2021

Add your own answers!

Related Questions

Calculating wealth values from richness in QGIS

1  Asked on March 11, 2021 by asiel-cabrera-guerrero


Adding site photos to a print composer atlas in QGIS

2  Asked on March 11, 2021 by mattimusaurelius


QGIS: exporting contours to DXF with height values

1  Asked on March 11, 2021 by sch751


Clear QGIS plot results window

1  Asked on March 11, 2021


Gdal_polygonize and gdaltindex error

1  Asked on March 10, 2021 by omkar-kadlag


Resizing a marker icon in OpenLayers 6

1  Asked on March 10, 2021 by spj_uk


Removing both sets of duplicate points

2  Asked on March 10, 2021


Ask a Question

Get help from others!

© 2021 All rights reserved.