I would like to add a OSM Standard Basemap to my project through a python script running in PyCharm, outside of QGIS. Within QGIS, I use QuickMapServices and add an OSM Standard Map but I can not seem to find anywhere how to retrieve the information from this plugin. Ultimately, I would like to know some code from a script that adds a base map to my project. I have tried using the code below but it says it is valid. However, no map appears in my project.
import glob
import json
import math
import os
import sys
from qgis.core import *
from PyQt5.QtGui import QColor
from PyQt5.QtGui import QFont
from qgis.core import QgsRasterLayer
from qgis.core import QgsVectorLayer
from qgis.core import QgsApplication
from qgis.core import QgsProcessingFeedback
from qgis.analysis import QgsNativeAlgorithms
from qgis._gui import QgsMapCanvas
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\OSGEO4W64\apps\Qt5\plugins'
os.environ['PATH'] += r';C:\OSGEO4W64\apps\qgis\bin;C:\OSGEO4W64\apps\Qt5\bin'
os.environ['PROJ_LIB'] = 'C:\\OSGeo4W64\\share\\proj'
QgsApplication.setPrefixPath("C:/OSGeo4W64/bin/qgis-bin.exe", True)
qgs = QgsApplication([], True)
qgs.initQgis()
sys.path.extend([r'C:\OSGEO4W64\apps\qgis\python',r'C:\OSGEO4W64\apps\Python37\lib\site-packages'])
sys.path.append('C:/OSGeo4W64/apps/qgis/python/plugins')
from qgis import processing
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
# Write your code here to load some layers, use processing
# algorithms, etc.
DistInt = {}
# Add Base Map
urlWithParams = 'type=xyz&url=https://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857'
rlayer2 = iface.addRasterLayer(urlWithParams, 'OpenStreetMap', 'wms')
if rlayer2.isValid():
QgsProject.instance().addMapLayer(rlayer2)
else:
print('invalid layer')
iface.addRasterLayer
should beQgsRasterLayer
(adapt import).iface
not available in standalone application. You may adapt my script to troubleshot your own issue. PS: on Linux so, less environment variables than you