I can load WMS layers by coding on QGIS Python console, those are the codelines:
# Google Satelite URL wms
url = 'type=xyz&url=http%3A//mt1.google.com/vt/lyrs%3Dy%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D'
# Constructing layer thoughout wms url
layer = QgsRasterLayer(url, 'Google Satelite', 'wms')
# Add this layer to the current project
QgsProject.instance().addMapLayer(layer)
I use QGIS 3.16 in a Ubuntu Linux VM. When I type these line of code on QGIS console this is what I get:
The problem occur when I try execute the same lines in a standalone script (using PyCharm IDE) and after load WMS layer I save a copy of this project, those are the lines i run in PyCharm standalone script:
from qgis.core import QgsApplication, QgsProject
import requests
# QGIS instalation folder path
QgsApplication.setPrefixPath('/usr/qgis', True)
# QGIS reference
qgs = QgsApplication([], True)
# Initiating QGIS
qgs.initQgis()
# Creating a variable to my qgis project
project = QgsProject.instance()
# Read a specific project
### DOWNLOAD https://drive.google.com/file/d/1Pqk5W3y47Mt4rjlN1QzGoarBGGl6B3og/view?usp=sharing
project.read('path/to/qgisproject/with/0001_tester/layout/0001.qgz')
# google satelite image WMS url
# class googleWMS:
url = "http://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}"
uri = "type=xyz&url="+requests.utils.quote(url)
# Create a layer from WMS url
tms_layer = QgsRasterLayer(uri, "Google Satelite", 'wms')
# Add this layer into project
QgsProject.instance().addMapLayer(tms_layer)
# Save the project in another location
QgsProject.instance().write('path/to/qgisproject.qgz')
The script can load the layer into qgis project and save the file, but the WMS layer is broken... No image is loaded to workspace.
tms_layer.isValid()
if is False the url params is bad or the wms provider dont load corrrect after you load the providers in this line:qgs.initQgis()
you need to print the providers with:print(QgsProviderRegistry.instance().providerList())
Check if the wms provider is there