Iterating over layers

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.

Getting ready

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.

How to do it...

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:

  1. First, let's open the polygon and the point layer using the QGIS Python Console:
    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")
    
  2. Next, get the map layer registry instance:
    registry = QgsMapLayerRegistry.instance()
    
  3. Now add the vector layers to the map:
    registry.addMapLayers([lyr_2, lyr_1])
    
  4. Then, we retrieve the layers as an interator:
    layers = registry.mapLayers()
    
  5. Finally, we loop through the layers and print the titles:
    for l in layers:
      printl.title()
    
  6. Verify that you can read the layer titles in the Python Console, similar to the following format:
    Cities20140904160234792
    Mississippi20140904160234635
    

How it works...

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.

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

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