4

I'm trying to get the current map scale in PyQGIS, running outside QGIS, with:

project = QgsProject.instance()
root = project.layerTreeRoot()
canvas = QgsMapCanvas()
bridge = QgsLayerTreeMapCanvasBridge(root, canvas)
# project.read(projectpath)
canvas.center()
canvas.extent()
canvas.scale()

The center and the extent are just perfect! But the scale is quite different from the one reported at QGIS bottom bar.

Testing the same in QGIS gives the same result.

How do I get the current map scale in PyQGIS (3.x)?

I'm using a project coordinate system, using meters.

example

3
  • 2
    iface.mapCanvas().scale() works in Python console.
    – jgrocha
    Dec 10, 2019 at 23:37
  • I've followed the documentation docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/…
    – jgrocha
    Dec 10, 2019 at 23:42
  • Are the canvases different sizes? Try iface.mapCanvas().size() in the python console and canvas.size() and see if you get the same result.
    – ian
    Dec 11, 2019 at 9:21

1 Answer 1

5

You need the canvas to be the same size for the scale to be the same.

Here is the small fragment of code

project = QgsProject.instance()
root = project.layerTreeRoot()
canvas = QgsMapCanvas()
bridge = QgsLayerTreeMapCanvasBridge(root, canvas)

canvas.setExtent(iface.mapCanvas().extent())
canvas.setCenter(iface.mapCanvas().center())
canvas.resize(iface.mapCanvas().size())

canvas.show()
canvas.scale()
#canvas.hide()

enter image description here

4
  • Something if not working on my side (QGIS 3.11.0-Master. iface.mapCanvas().scale() works pretty well, but using another canvas with the same extend, center and size fails: canvas.scale() = 9353194300.573679.
    – jgrocha
    Dec 11, 2019 at 17:52
  • Something strange is going on in QGIS 3.4.12 too. If I use the commands in the answer posted above I get a canvas.scale of 765592971.6097143 when my project has a scale of 10,000. If I set the scale of the canvas to iface.mapCanvas().scale() (ie 10,000) canvas.scale() reports the correct scale, but the extent is no longer correct!
    – ian
    Dec 11, 2019 at 19:35
  • It's strange but using show() and after hide() also happens?
    – Fran Raga
    Dec 11, 2019 at 20:59
  • Yes, if I run canvas.scale() before show() and hide() I get 1141189523.5122857 and after show() and hide() 765592971.6097143. So show and hide changes the reported scale but unfortunately doesn't make it produce the expected answer
    – ian
    Dec 12, 2019 at 17:34

Your Answer

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

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