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

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 the following URL:

https://github.com/GeospatialPython/Learn/raw/master/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:

  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',
                                       'Polyon' , "ogr") 
            vectorLyr.isValid() 
    
  4. Next, access the layer's data provider:
            vpr = vectorLyr.dataProvider() 
    
  5. Now, we build a list of points for the polygon:
            points = [] 
            points.append(QgsPoint(-123.26072,49.06822)) 
            points.append(QgsPoint(-127.19157,43.07367)) 
            points.append(QgsPoint(-120.70567,35.21197)) 
            points.append(QgsPoint(-115.89037,40.02726)) 
            points.append(QgsPoint(-113.04051,48.47859)) 
            points.append(QgsPoint(-123.26072,49.06822)) 
    
  6. Now, we create a geometry object and ingest the points as a polygon:
            poly = QgsGeometry.fromPolygon([points]) 
    
  7. Next, we build the feature object and add the points:
            f = QgsFeature() 
            f.setGeometry(poly) 
    
  8. Finally, we add the feature to the layer's data provider and update the extents:
            vpr.addFeatures([f]) 
    

How it works...

Adding a polygon is very similar to adding a line, but with one key difference that is a common pitfall. The last point must be identical to the first point in order to close the polygon. If you don't repeat the first point, you won't receive any errors, but the polygon will not display in QGIS, which can be difficult to troubleshoot.