QGIS Python Programming Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Loading a vector layer from a file sample

Vector data stored in a local file is one of the most common geospatial data formats. Vector data typically stores geometry with associated attributes. In this recipe, we'll load a vector data file, in this case a shapefile, as a vector layer in QGIS.

Getting ready

For ease of following the examples in this book, it is recommended that you create a directory called qgis_data in your root or user directory,which will provide a short pathname. This setup will help prevent the occurrence of any frustrating errors resulting from path-related issues on a given system. In this recipe, and others, we'll use a point shapefile of the New York City museums, which you can download from https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip.

Unzip this file and place the shapefile's contents in a directory named nyc within your qgis_data directory.

How to do it...

Now, we'll walk through the steps of loading a shapefile and adding it to the map, as follows:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. In the Python console, create the layer:
            layer = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp",
                                   "New York City Museums", "ogr") 
    
  4. Next, ensure that the layer is created as expected:
            if not layer.isValid(): 
                print("Layer {} did not load".format(layer.name()))
  5. Finally, add the layer to the layer registry:
            QgsMapLayerRegistry.instance().addMapLayers([layer]) 
    
  6. Verify that your QGIS map looks similar to the following image:

    How to do it...

How it works...

The QgsVectorLayer object requires the location of the file, a name for the layer in QGIS, and a data provider that provides the right parser and capabilities managed for the file format. Most vector layers are covered by the ogr data provider, which attempts to guess the format from the file name extension in order to use the appropriate driver. The possible formats available for this data provider are listed at http://www.gdal.org/ogr_formats.html. You can see which drivers you have installed using the following code:

    drivers = [ogr.GetDriver(n).GetName() for n in
              range(ogr.GetDriverCount())] 
    print(drivers) 

Once we have created the QgsVector object, we do a quick check using the layer.isValid() method to see whether the file was loaded properly. We won't use this method in every recipe to keep the code short; however, this method is often very important. It's usually the only indication that something has gone wrong. If you have a typo in the filename or you try to connect to an online data source but have no network connection, you won't see any errors. Your first indication will be another method failing further into your code, which will make tracking down the root cause more difficult.

In the last line, we add the vector layer to QgsMapLayerRegistry, which makes it available on the map. The registry keeps track of all the layers in the project. The reason why QGIS works this way is so you can load multiple layers, style them, filter them, and do other operations before exposing them to the user on the map.