Loading a vector layer from a file sample

This recipe describes the most common type of data used in QGIS, a file. In most cases, you'll start a QGIS project by loading a shapefile.

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 provides 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 New York City museums, which you can download from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.

Unzip this file and place the shapfile'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 was created as expected:
    if not layer.isValid():
      print "Layer %s did not load" % layer.name()
    
  5. Finally, add the layer to the layer registry:
    QgsMapLayerRegistry.instance().addMapLayers([layer])
    

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 formats available with this data provider are listed at http://www.gdal.org/ogr_formats.html.

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, but 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 the 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.

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

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