Aller au contenu | Aller au menu | Aller à la recherche

Need to stick to some scales in QGIS ?

My colleague, Michaël, would like to be able in QGIS to force the canvas scales to some predefined ones. Since we now have project scales (and QGIS pre-defined scales) in the scale selector, we could use them, and add a simple checkbox near the combobox Stick to predefined scales.

The aim is to force the canvas to render only at these scales. For example, if a QGIS user uses the rectangle zoom tool, and he should go to 1/56003, he would instead land on 1/50000, the closest pre-defined scale.

He made a little python script as a proof of concept to illustrate it:

# -*- coding: utf-8 -*-

# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *

class forcedScale():
    
    # pre-defined scales
    # has to be read from project properties
    predefinedScales = [
        5000,
        10000,
        25000,
        50000,
        100000,
        250000,
        500000
    ]
    
    # mapCanvas
    mc = None
    
    def init( self ):
        '''
        Initialize class instance
        '''
        mc = iface.mapCanvas()
        self.mc = mc
        self.mc.scaleChanged.connect(self.setScale)

   def setScale( self, scale ):
       targetScale = min(
           self.predefinedScales, 
           key=lambda x:abs(x-scale)
       )
       self.mc.zoomScale( targetScale )

In this script, he hard coded the scales, but obviously we should get them from the project properties.

Run this script in the QGIS Python console and initialize with fs = forcedScale() to stick to scales.

A discussion has been opened in QGIS-Dev mailing list : http://osgeo-org.1560.x6.nabble.com/Force-canvas-to-predefined-scales-help-needed-to-improve-a-script-td5201783.html

Commentaires

1. Le vendredi 17 avril 2015, 14:31 par kimaidou

Improve version here:
https://gist.github.com/mdouchin/72...

with:

* "replayed" variable to avoid probable infinite loop
* you can now initialize the method with a python list of scales you want to force canvas to, for example:

fs = forcedScale( [25000, 50000, 100000 ] )