Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding a polygon feature to a vector layer


In this recipe, we'll add a polygon to a layer. A polygon is the most complex kind of geometry. However, in QGIS, the API is very similar to a line.

Getting ready

For this recipe, we'll use a simple polygon shapefile, which you can download as a ZIP file from https://geospatialpython.googlecode.com/files/polygon.zip.

Extract this shapefile to a folder called polygon in your /qgis_data directory.

How to do it...

This recipe will follow the standard PyQGIS process of loading a layer, building a feature, and adding it to the layer's data provider, as follows:

  1. Start QGIS.

  2. From the Plugins menu, select Python Console.

  3. First, load the layer and validate it:

    vectorLyr =  QgsVectorLayer('/qgis_data/polygon/polygon.shp', 'Polygon' , "ogr")
    vectorLyr.isValid()
    
  4. Next, access the layer's data provider:

    vpr = vectorLyr.dataProvider()
    
  5. Now, build a list of points for the polygon:

    points = []
    points.append(QgsPoint(-123.26,49.06))
    points.append(QgsPoint(-127.19,43.07))
    points...