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 filesystem feature to load a tiled layer.

Getting ready

You don't need to do any preparation for this recipe, other than opening the Python console plugin within QGIS.

How to do it...

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:

  1. First, we import the GDAL library:
    from osgeo import gdal
    
  2. Next, we'll create our XML template, describing the OpenStreetMap tiled web service:
    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>"""
  3. Now, we'll create the path for our GDAL virtual filesystem's file:
    vfn = "/vsimem/osm.xml"
    
  4. Next, we use GDAL to create the virtual file using the path and the XML document:
    gdal.FileFromMemBuffer(vfn, xml)
    
  5. Now, we can create a raster layer from the virtual file:
    rasterLyr = QgsRasterLayer(vfn, "OSM")
    
  6. Before we add the layer to the map, we'll make sure that it's valid:
    rasterLyr.isValid()
    
  7. Finally, add the layer to the map:
    QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
    

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset