1

I'm using PyQGIS to add QgsRasterLayer layers to my project.

This is how I create the layer:

urlWithParams = "type=xyz&url=http://ecn.t3.tiles.virtualearth.net/tiles/a%7Bq%7D.jpeg?g=1"
rlayer = QgsRasterLayer(urlWithParams, "Bing maps", "wms")

I can set their max zoom level via the QGIS UI (Properties -> Source -> Max Zoom Level, see attached image), but I'd like to do it programmatically via PyQGIS. I've found that this class has the setMaxZoomLevel method:

https://www.qgis.org/pyqgis/master/core/QgsVectorTileBasicRendererStyle.html

but I cannot find how to go from a QgsRasterLayer to its QgsVectorTileBasicRendererStyle.

Has anyone done it?

enter image description here

0

2 Answers 2

2

I analyzed the source of the layer and saw, that the "min/max zoom level" are stored in the DataSourceUrl as the zmin/zmax parameters:

print(iface.activeLayer().source())

type=xyz&url=https://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=18&zmin=1

You can replace the zmin/zmax values (i.e. using regex):

import re

layer = iface.activeLayer()
current_source = layer.source()
print(current_source)

new_zmin = 1
new_zmax = 18

updated_source = re.sub(r'zmin=\d+', f'zmin={new_zmin}', current_source)
updated_source = re.sub(r'zmax=\d+', f'zmax={new_zmax}', updated_source)

layer.setDataSource(updated_source, layer.name(), "wms")

layer.triggerRepaint()

Result: enter image description here

4
  • I've added a screenshot of the max zoom level setting. In this case for an OpenStreetMap layer. The zoom level refers to this scale: wiki.openstreetmap.org/wiki/Zoom_levels The scale solution you proposed didn't work. It made the whole map go away. Commented Nov 12 at 14:46
  • Thank you so much, that did it. Actually, it was much easier, as I'm building the data source URL myself, so just adding &zmax=20&zmin=1 to the URL sets the zoom levels. Commented Nov 12 at 15:58
  • Why has the question been closed as "off-topic"? Just trying to understand what is off/on topic. Isn't it addressing a problem that other people may encounter? Commented Nov 13 at 9:18
  • I agree with you that it might be interesting for other users. I think it was closed because you havnt provided any code example. If you update your question, it may be re-opened.
    – juto96
    Commented Nov 13 at 10:31
0

@DidacBusquets answered his/her own question:

The following code does set the maximum and minimum levels of the layer (by appending it to the URL):

"type=xyz&url=http://ecn.t3.tiles.virtualearth.net/tiles/a%7Bq%7D.jpeg?g=1&zmin=1&zmax=20"
rlayer = QgsRasterLayer(urlWithParams, "Bing maps", "wms")

Your Answer

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

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