Last active
September 4, 2015 04:08
-
-
Save mdouchin/72a09b629a5557c1dc1c to your computer and use it in GitHub Desktop.
QGIS python script : zoom only to pre-defined scales
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a different way: