Learn how to use the OpenStreetMap Service in QGIS using Python from this section as part of this preview chapter, Creating Dynamic Maps from QGIS Python Programming CookBook. With 140 short, reusable recipes to automate geospatial processes in QGIS, the QGIS Python Programming CookBook teaches readers how to use Python and QGIS to create and transform data, produce appealing GIS visualizations, and build complex map layouts.
Using the OpenStreetMap Service
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 file system feature to load a tiled layer.
You don’t need to do any preparation for this recipe other than to open the Python Console plugin within QGIS.
How to do it…
We will create an XML template describing 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.
- First we import the GDAL library;
fromosgeo import gdal
- Next we’ll create our XML template describing the OpenStreetMap tiled web service:
xml = “””<GDAL_WMS>
- Now we’ll create the path for our GDAL virtual file system file:
vfn = “/vsimem/osm.xml”
- Next we use GDAL to create the virtual file using the path and the XML document:
- Now can create a raster layer from the virtual file:
rasterLyr = QgsRasterLayer(vfn, “OSM”)
- Before we add the layer to the map, we’ll make sure it’s valid:
- Finally add the layer to the map:
How it works…
There are other ways to load tiled map services like OpenStreetMap into QGIS programmatically but GDAL is by far the most robust. The prefix, vsimem, tells GDAL to use a virtual file to manage the tiles. This approach frees you from having to manage downloaded tiles on disk directly and focus on your application’s functionality.