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

Adding a point feature to a vector layer

This recipe performs the simplest possible edit to a vector layer instantiated from a shapefile. We will add a point to an existing point layer.

Getting ready

For this recipe, download the following zipped shapefile:

https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip

Extract the .shp, .shx, and .dbf files to the directory /qgis_data/nyc.

How to do it...

We will load the vector layer from the shapefile, create a new geometry object as a point, create a new feature, set the geometry, and add it to the layer's data provider. Finally, we will update the extents of the layer to make sure the bounding box of the layer encapsulates the new point:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. First, load the layer:
            vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp',
                                       'Museums' , "ogr") 
    
  4. Now, we will access the layer's data provider:
            vpr = vectorLyr.dataProvider() 
    
  5. Next, create a new point using the QgsGeometry API:
            pnt = QgsGeometry.fromPoint(QgsPoint(-74.80,40.549)) 
    
  6. Now, we will create a new QgsFeature object to house the geometry:
            f = QgsFeature() 
    
  7. Next, set the geometry of the feature using our point:
            f.setGeometry(pnt) 
    
  8. Then, we place the features into the layer's feature list:
            vpr.addFeatures([f]) 
    
  9. Finally, we update the layer extents to complete the addition:
            vectorLyr.updateExtents() 
    
  10. The following screenshot shows the added point on the far left of the image:

    How to do it...

How it works...

PyQGIS abstracts the points within a layer into four levels. At the lowest level is the QgsPoint object, which contains nothing more than the coordinates of the point. That object is added to an abstract QgsGeometry object. That object becomes the geometry half of a QgsFeature object, which also has the ability to store and manage attributes. All the features are managed by the QgsVectorLayer's QgsDataProvider object. The data provider manages both the spatial and non-spatial parts of a layer to separate that aspect from styling and other presentation-related portions.

There's more...

When adding any feature to a layer, if the data source is a database such as PostGIS, the addFeatures() method will return true even if there is an insert error in the database. Insert errors can include common configurations, such as foreign key constraints. If you find you are unable to add a feature, try inserting the feature into the database manually, using SQL to troubleshoot.