Skip to content

Instantly share code, notes, and snippets.

@mdouchin
Last active September 4, 2015 04:08
Show Gist options
  • Save mdouchin/72a09b629a5557c1dc1c to your computer and use it in GitHub Desktop.
Save mdouchin/72a09b629a5557c1dc1c to your computer and use it in GitHub Desktop.
QGIS python script : zoom only to pre-defined scales
# -*- coding: utf-8 -*-
# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from qgis.core import *
class forcedScale():
# pre-defined scales
predefinedScales = [
5000,
10000,
25000,
50000,
100000,
250000,
500000
]
# mapCanvas
mc = None
# avoid loop
replayed = False
def __init__( self, *predefinedScales ):
'''
Initialize class instance
'''
mc = iface.mapCanvas()
self.mc = mc
self.mc.scaleChanged.connect(self.setScale)
if predefinedScales:
self.predefinedScales = predefinedScales
def setScale( self, scale ):
if self.replayed:
return
print "initial scale: %s" % scale
targetScale = min(
self.predefinedScales,
key=lambda x:abs(x-scale)
)
if targetScale == scale:
return
self.replayed = True
print "zoom to %s" % targetScale
self.mc.zoomScale( targetScale )
self.replayed = False
# You can instanciate this class this way
# fs = forcedScale()
# which will use the scales defined in the property predefinedScales of the class,
# or you can provide a list of scales like this
# fs = forcedScale( 25000, 50000, 100000 )
@NathanW2
Copy link

Here is a different way:

def forcedScale(*scales):
    def setScale(scale ):
        iface.mapCanvas().scaleChanged.disconnect(setScale)

        print "initial scale: %s" % scale

        targetScale = min(
            scales, 
            key=lambda x:abs(x-scale)
        )
        if targetScale == scale:
            return

        print "zoom to %s" % targetScale
        iface.mapCanvas().zoomScale( targetScale )
        iface.mapCanvas().scaleChanged.connect(setScale)

    # pre-defined scales
    predefinedScales = [
        5000,
        10000,
        25000,
        50000,
        100000,
        250000,
        500000
    ]

    # avoid loop

    iface.mapCanvas().scaleChanged.connect(setScale)

    if not scales:
        scales = predefinedScales

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment