The QGSRasterLayer
API provides a convenient, high-level interface to raster data. To use this interface, we must load a layer into QGIS. The API allows you to work with a layer without adding it to the map. In this way, we'll load layer and then add it to the map.
As with the other recipes in this book, you need to create a directory called qgis_data
in our root or user directory, which provides a short pathname without spaces. This setup will help prevent any frustrating errors that result from path-related issues on a given system. In this recipe, and the others, we'll use a Landsat satellite image of the Mississippi Gulf Coast, which you can download from https://geospatialpython.googlecode.com/files/SatImage.zip.
Unzip the SatImage.tif
and SatImage.tfw
files and place them in a directory named rasters
within your qgis_data
directory.
Now, we'll go through how to load a raster layer and then step by step add it to the map
rasterLyr = QgsRasterLayer("/qgis_data/rasters/SatImage.tif", "Gulf Coast")
True
:rasterLyr.isValid()
QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
The QgsRasterLayer
object requires the location of the file and a name for the layer in QGIS. The underlying GDAL library determines the appropriate method of loading the layer. This approach contrasts with the QgsVectorLayer()
method, which requires you to specify a data provider. Raster layers also have a data provider, but unlike vector layers, all raster layers are managed through GDAL. One of the best features of QGIS is that it combines the best of breed open source geospatial tools into one package. GDAL can be used as a library as we are using it here from Python or as a command-line tool.
Once we have created the QgsRasterLayer
object, we do a quick check using the rasterLayer.isValid()
method to see whether the file was loaded properly. This method will return True
if the layer is valid. We won't use this method in every recipe; however, it is a best practice, especially when building dynamic applications that accept user input. Because most of the PyQGIS API is built around C libraries, many methods do not throw exceptions if an operation fails. You must use specialized methods to verify the output.
Finally, we add the layer to the map layer registry, which makes it available on the map and in the legend. The registry keeps track of all the loaded layers by separating, loading, and visualizing the layers. QGIS allows you to work behind the scenes in order to perform unlimited intermediate processes on a layer before adding the final product to the map.