For many GIS operations, you need to loop through the map layers to look for specific information or to apply a change to all the layers. In this recipe, we'll loop through the layers and get information about them.
We'll need two layers in the same map projection to perform this recipe. You can download the first layer as a ZIP file from https://geospatialpython.googlecode.com/files/MSCities_Geo_Pts.zip.
You can download the second zipped layer from https://geospatialpython.googlecode.com/files/Mississippi.zip.
Unzip both of these layers into a directory named ms
within your qgis_data
directory.
We will add the layers to the map through the map registry. Then, we will iterate through the map layers and print each layer's title. To do this, perform the following steps:
lyr_1 = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/mississippi.shp", "Mississippi", "ogr") lyr_2 = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/MSCities_Geo_Pts.shp", "Cities", "ogr")
registry = QgsMapLayerRegistry.instance()
registry.addMapLayers([lyr_2, lyr_1])
layers = registry.mapLayers()
for l in layers: printl.title()
Cities20140904160234792 Mississippi20140904160234635
Layers in QGIS are independent of the map canvas until you add them to the map layer registry. They have an ID as soon as they are created. When added to the map, they become part of the canvas, where they pick up titles, symbols, and many other attributes. In this case, you can use the map layer registry to iterate through them and access them to change the way they look or to add and extract data.