TransWikia.com

Accessing and using the QuickMapServices Plugin externally (outside of QGIS)

Geographic Information Systems Asked on January 28, 2021

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:OSGEO4W64appsQt5plugins'
    os.environ['PATH'] += r';C:OSGEO4W64appsqgisbin;C:OSGEO4W64appsQt5bin'
    os.environ['PROJ_LIB'] = 'C:OSGeo4W64shareproj'
    
    QgsApplication.setPrefixPath("C:/OSGeo4W64/bin/qgis-bin.exe", True)
    qgs = QgsApplication([], True)
    qgs.initQgis()
    
    sys.path.extend([r'C:OSGEO4W64appsqgispython',r'C:OSGEO4W64appsPython37libsite-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')

One Answer

We don't know that the other parts of your code look like. So it is hard to provide a perfect answer. But the followings will give you an idea. It worked for me in the project with GUI.

from qgis.gui import QgsLayerTreeMapCanvasBridge

...

canvas = QgsMapCanvas()
root = QgsProject.instance().layerTreeRoot()
bridge = QgsLayerTreeMapCanvasBridge(root, canvas)

...

Answered by Kadir Şahbaz on January 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP