pythongoogle-mapsqgis

How to get a google basemap in a python code for QGIS?


I'm creating a python plugin for different users that has the layers that each person need to use and work with in QGIS.

I have no trouble adding rasters from Geoserver using the following code:

        wmsTicketDSM= QgsRasterLayer('contextualWMSLegend=0&crs=EPSG:27700&dpiMode=7&featureCount=10&format=image/png&layers=Ticket_DSM&password=XXXXXXXXXXXX&styles=&url=http://63.12.21.231:8080/geoserver/exchange_maps/wms&username=admin', 'Ticket_DSM', 'wms')
        if not wmsTicketDSM.isValid():
            print "Layer wmsTicketDSM failed to load!"
        else:
            print "Raster Layer wmsTicketDSM loaded!"
        QgsMapLayerRegistry.instance().addMapLayer(wmsTicketDSM,False)

Now I need to add basemaps. How to add a Google Satellite map on python?


Solution

  • Google maps can be used as basemaps in Qgis loading them as TMS (Tiled Map Service). From QGIS 2.18 The native support To TMS has been added to Qgis by Lutra.

    import requests
    service_url = "https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}"
    service_uri = "type=xyz&zmin=0&zmax=21&url="+requests.utils.quote(service_url)
    tms_layer = core.QgsRasterLayer(service_uri, "Google Hybrid", "wms")
    

    where lyrs=y stay for hybrid map, lyrs=s for sat map and lyrs=m for road map.

    Note that the url parameter of the uri has to be percent codes encoded

    QGIS previous releases could be supported making use of TileLayerPlugin by Minoru Akagi that exposes the needed methods:

    plugin = qgis.utils.plugins.get("TileLayerPlugin")
    if plugin:
      from TileLayerPlugin.tiles import BoundingBox, TileLayerDefinition
      bbox = None    # BoundingBox(-180, -85.05, 180, 85.05)
      layerdef = TileLayerDefinition(u"title",
                                     u"attribution",
                                     "http://example.com/xyz/{z}/{x}/{y}.png",
                                     zmin=1,
                                     zmax=18,
                                     bbox=bbox)
      plugin.addTileLayer(layerdef)
    else:
      from PyQt4.QtGui import QMessageBox
      QMessageBox.warning(None,
                          u"TileLayerPlugin not installed",
                          u"Please install it and try again.")
    

    For Google basemaps replace the proper "attribution" row and the url row with the following:

    "https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}"