InsideDarkWeb.com

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 =[]
points.append(QgsPoint(-1232443,1318350))
points.append(QgsPoint(-1332443,1418350))
points.append(QgsPoint(-1432443,1518350))


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

#This is how I am adding points and plotting them. (Just for testing)
points.append(QgsPoint(-1532443,1618350))
polyline.setToGeometry(QgsGeometry.fromPolyline(points), None)
points.append(QgsPoint(-1632443,1718350))
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:

canvas.setExtent(polyline.asGeometry().boundingBox())

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:

canvas.refresh()

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 InsideDarkWeb.com. All rights reserved.