1

I'm trying to answer my own question asked here, but which has not found favour: In QGIS save a view like a bookmark based on center and scale

I thought I might be able to work backwards, by defining screen center (centre) and screen scale, then working backwards to get the geographic extents. Note I'm a Python novice and have never tackled PyQGIS before.

Screen centre turned out to be trivial (so long as points were in correct units for the CRS):

canvas = qgis.utils.iface.mapCanvas()
center = QgsPointXY(44, 42)
canvas.setCenter(center)

I naively thought I could do a similar trick with setScale, but this gives the error 'QgsMapCanvas' object has no attribute 'setScale' no matter what I try.

I know I can change the display scale using lines like this:

canvas.resize(QSize(3920,4080))

However, this changes the scale by changing the window extent, which is not what I want. How can I do this?

2

I think the method you are looking for is canvas.zoomScale(). Here is a simple code snippet to get the current canvas center and scale:

canvas = iface.mapCanvas()
centre = canvas.extent().center()
current_scale = canvas.scale()

And to set the center and scale (e.g. run the lines above in the console editor, then comment them out, manually change the zoom and extent then run the lines below):

canvas.setCenter(centre)
canvas.zoomScale(current_scale)

Or, hardcoding the values as you did with the center:

canvas.setCenter(QgsPointXY(44, 42))
canvas.zoomScale(1500000)
1
  • thanks. I note doing this I can also define "newscale" in scientific notation and then excute canvas.zoomScale(newscale) which avoids having to count zeros. Apr 21 '20 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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