PyQGIS – Add Vector Tile Layer with Styling from styleUrl (OGC API – Tiles)

ogc-apipyqgisstylevector-tiles

I have an OGC API endpoint that serves vector tiles in mvt. I have succeeded in adding this vector tile layer using the GUI by setting up a connection with:

Layer > Add Layer > Add Vector Tile Layer > New Generic Connection

And filling in the URL, zoom levels and Style URL. The styles URL conforms the OGC API standard for styles at <url>/styles/<style_name>. Anyway, it works and the result is as desired.

However, when I try to add the same vector tile layer from a Python script, the vector tile layer does not have the correct styling. I added this layer by creating a layer:

from qgis.core import QgsVectorTileLayer

uri = f"styleUrl={styleUrl}&type={type}&url={url}&zmax={zmax}&zmin={zmin}&http-header:referer={http_header}"
layer = QgsVectorTileLayer(uri, f"{title} (OAT)")

Afterwards adding this layer to the project. Here, the styleUrl, type, url, zmax, zmin and http_header are the same as when adding via the GUI.

When comparing the layers in the explorer and opening the layer properties, the General, Information from provider and CRS sections are identical for both layers, namely the URL, source, Provider, Source type, and Zoom levels values. Because of this, I find it strange that the styleUrl is somehow not passed on in this way.

At this point, I am mainly wondering if it is possible to add styling using styleUrl via PyQGIS and whether there is another way to add the styling to the layer from the script. Perhaps this functionality is somehow not yet supported in QGIS 3.30.

If anyone did succeed in adding styling to an (OGC API) vector tile layer via Python API/plugin.

Best Answer

I resolved this problem by simply adding: layer.loadDefaultStyle() This loads the styling from the styleUrl and adds it to the VT layer.

Related Question