Cloud-based technology is moving more and more data to the Internet, and GIS is no exception. QGIS can load web-based data using Open GIS Consortium standards, such as Web Map Service (WMS). The easiest way to add WMS layers is using the Geospatial Data Abstraction Library (GDAL) and its virtual filesystem feature to load a tiled layer.
You don't need to do any preparation for this recipe, other than opening the Python console plugin within QGIS.
We will create an XML template that describes the tiled web service from OpenStreetMap we want to import. Then, we'll turn it into a GDAL virtual file and load it as a QGIS raster layer. To do this, we need to perform the following steps:
from osgeo import gdal
xml = """<GDAL_WMS> <Service name="TMS"> <ServerUrl>http://tile.openstreetmap.org/${z}/${x}/${y}.png</ServerUrl> </Service> <DataWindow> <UpperLeftX>-20037508.34</UpperLeftX> <UpperLeftY>20037508.34</UpperLeftY> <LowerRightX>20037508.34</LowerRightX> <LowerRightY>-20037508.34</LowerRightY> <TileLevel>18</TileLevel> <TileCountX>1</TileCountX> <TileCountY>1</TileCountY> <YOrigin>top</YOrigin> </DataWindow> <Projection>EPSG:900913</Projection> <BlockSizeX>256</BlockSizeX> <BlockSizeY>256</BlockSizeY> <BandsCount>3</BandsCount> <Cache /> </GDAL_WMS>"""
vfn = "/vsimem/osm.xml"
gdal.FileFromMemBuffer(vfn, xml)
rasterLyr = QgsRasterLayer(vfn, "OSM")
rasterLyr.isValid()
QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
There are other ways to load tiled map services such as OpenStreetMap into QGIS programmatically, but GDAL is by far the most robust. The prefix vsimem
tells GDAL to use a virtual file in order to manage the tiles. This approach frees you from the need to manage downloaded tiles on disk directly and allows you to focus on your application's functionality.