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

Creating a vector layer in memory

Sometimes you need to create a temporary dataset for a quick output, or as an intermediate step in a more complex operation without the overhead of actually writing a file to disk. PyQGIS employs memory layers that allow you to create a complete vector dataset, including the geometry, fields, and attributes, virtually. Once the memory layer is created, you can work with it the same way you would with a vector layer loaded from the disk.

Getting ready

This recipe runs entirely inside the PyQGIS console, so no preparation or outside resources are required.

How to do it...

We will create a point vector layer with a few fields named Layer 1 and then validate it:

  1. Start QGIS.
  2. From the Plugins menu select Python Console.
  3. In the Python console, create a QgsVectorLayer, including fields, and specify it as type memory:
            vectorLyr = QgsVectorLayer('Point?crs=epsg:4326
                                       &field=city:string(25)
                                       &field=population:nt',
                                       'Layer 1' , "memory")  
    
  4. Now, validate the layer and ensure the console returns True:
            vectorLyr.isValid() 
    

How it works...

The QgsVectorLayer requires three arguments. The last one specifies the type, in this case, memory. The second one specifies the layer name. Normally, the first argument is the path to the file on the disk used to create the layer. In the case of a memory layer, the first argument becomes the construction string for the layer. The format uses query parameters following the convention of key=value. In this case, we specify the first field, a string for city names, and then an integer field for population.