官术网_书友最值得收藏!

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 zipped shapefile from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.

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

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 extent of the layer to make sure that 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, will access the layer's data provider:
    vpr = vectorLyr.dataProvider()
    
  5. Next, create a new point using the QgsGeometry object:
    pnt = QgsGeometry.fromPoint(QgsPoint(-74.80,40.549))
    
  6. Now, 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, place the features into the layer's feature list:
    vpr.addFeatures([f])
    
  9. Finally, update the layer's extent to complete the addition:
    vectorLyr.updateExtents()
    

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. This object is added to an abstract QgsGeometry object. This object becomes the geometric part of a QgsFeature object, which also has the ability to store and manage attributes. All the features are managed by the QgsDataProvider object. The data provider manages the geospatial aspect of a layer to separate that aspect from styling and other presentation-related portions. QGIS has another editing approach in Python, which is called an editing buffer. When you use an editing buffer, the changes can be displayed, but they are not permanent until you commit them. The most common use case for this editing method is in GUI applications where the user may decide to roll back the changes by cancelling the editing session. The PyQGIS Developer Cookbook has an example of using and editing buffers in Python, and is available at http://docs.qgis.org/2.6/en/docs/pyqgis_developer_cookbook/vector.html.

主站蜘蛛池模板: 汶上县| 清水县| 南岸区| 六枝特区| 威远县| 梁山县| 方正县| 余庆县| 绥棱县| 商城县| 喀什市| 海林市| 汝城县| 海晏县| 溧阳市| 贵溪市| 普定县| 大姚县| 景谷| 上杭县| 北海市| 文昌市| 万盛区| 新丰县| 当雄县| 平江县| 清流县| 盱眙县| 拜泉县| 通化市| 土默特右旗| 当涂县| 拜泉县| 礼泉县| 东兰县| 万安县| 射阳县| 鄂温| 呼图壁县| 孙吴县| 周至县|