In another tutorial we already discussed how to add raster layer into QGIS. In this QGIS Python programming tutorial we move further to discuss about Data Provider in particular how to set a layer data source, reload and add it to QGIS map Canvas. This tutorial is using QGIS 3.0.
Let's say we have three basemap (OSM, Strava Heatmap and Stamen Terrain). We want to make a function to add and change the basemap. So we can call the function to set a different basemap without adding a new layer.
There are several steps to be done. Firstly we initiate three variables for the each basemap as follow:
Then we make a list for the URL and create a list for layer name.
Next we add an initial basemap to QGIS map canvas.
Now we create a function which is called change_basemap with an argument the name of layer name. In this function we do several steps such as: getting the index of url based on the layer name. Set the url of basemap layer with the new url. Reload it and refresh map canvas.
To set the new basemap url and reload it we are using setDataSourceUri method from QgsDataProvider class. Then we repaint the basemap raster layer with triggerRepaint method and reload it. To view the new basemap we have to refresh the map canvas using refresh method from the iface class. The complete change basemap function as follow.
The complete code can be seen below.
Save the code and run it. The OSM basemap will be added to QGIS map canvas. To change it, type in the python console change_basemap("Strava Heatmap") to change the basemap to Strava heatmap or change_basemap("Stamen Terrain") to change it into Strava terrain basemap. Let's see the action!That's all the tutorial how to set data source for a xyz tile basemap, reload it and see it in the QGIS. Please visit QGIS Python Programming Tutorial Series, If you want to explore more tutorials about QGIS Python programming.