More

Set predefined scales in PyQGIS for standalone application

Set predefined scales in PyQGIS for standalone application


I am trying to figure out how to set the zoom scales to match those meant for OpenStreetMaps and Google Maps, etc., as I am using OSM for a basemap. I've looked all over the internet and can't seem to find any support for this particular goal.

I have an XML document (scales.xml) with all of the scales needed, but I just can't figure out how to implement it:

                        

I've tried reworking some of the code from thr QuickMapServices plugin, but I get no results from it:

def _load_scales_list(self): scales_filename = os.path.join(self.plugin_dir, 'scales.xml') scales_list = [] xml_root = ET.parse(scales_filename).getroot() for scale_el in xml_root.findall('scale'): scales_list.append(scale_el.get('value')) return scales_list def scales_list(self): if not self._scales_list: self._scales_list = self._load_scales_list() return self._scales_list def set_nearest_scale(self): #get current scale curr_scale = self.mapCanvas().scale() #find nearest nearest_scale = sys.maxint for scale_str in self.scales_list: scale = scale_str.split(':')[1] scale_int = int(scale) if abs(scale_int-curr_scale) < abs(nearest_scale - curr_scale): nearest_scale = scale_int #set new scale if nearest_scale != sys.maxint: self.mapCanvas().zoomScale(nearest_scale)

This code neither throws an error nor does anything at all. Any ideas as to how I can get this working in a standalone window?


You should place the definition of the list of predefined scales in your init-method.

self.predefinedScale = [… ]

Then connect the scaleChanged event to the function actually setting the proper scale.

self.mapCanvas.scaleChanged.connect(self.zoomToScale)

Define this function as class method, not as local function of some other method, so that it will be executed in the global context.

def zoomToScale(self) self.mapCanvas.scaleChanged.disconnect(self.zoomToScale) scale = self.mapCanvas.scale() targetScale = min(self.predefinedScales, key=lambda x: abs(x - scale)) self.mapCanvas.zoomScale(targetScale) self.mapCanvas.scaleChanged.connect(self.zoomToScale)

you can define this scale in predefined scale for qgis

USING Python :

def forcedScale(scales): def zoomToScale(scale): self.iface.mapCanvas().scaleChanged.disconnect(zoomToScale) targetScale = min(scales, key=lambda x:abs(x-scale)) self.iface.mapCanvas().zoomScale( targetScale ) self.iface.mapCanvas().scaleChanged.connect(zoomToScale) predefinedScales = [ 591657528, 295828764, 147914382, 73957191, 36978595, 18489298, 9244649, 4622324, 2311162, 1155581, 577791, 288895, 144448, 72224, 36112, 18056, 9028, 4514, 2257, 1128, 564, 282, 141, 71 ] self.iface.mapCanvas().scaleChanged.connect(zoomToScale) scales = predefinedScales

Watch the video: QGIS mit Python starten.