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

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.append(QgsPoint(-120.70,35.21))
    points.append(QgsPoint(-115.89,40.02))
    points.append(QgsPoint(-113.04,48.47))
    points.append(QgsPoint(-123.26,49.06))
    
  6. Next, create a geometry object and ingest the points as a polygon. We nest our list of points in another list because a polygon can have inner rings, which will consist of additional lists of points being added to this list:
    poly = QgsGeometry.fromPolygon([points])
    
  7. Next, build the feature object and add the points:
    f = QgsFeature()
    f.setGeometry(poly)
    
  8. Finally, 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, 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 be displayed in QGIS, which can be difficult to troubleshoot.

主站蜘蛛池模板: 保德县| 沭阳县| 双牌县| 枣庄市| 长治县| 寿阳县| 临海市| 开阳县| 资溪县| 汨罗市| 确山县| 宜州市| 东乡族自治县| 西乌珠穆沁旗| 奉新县| 营口市| 手机| 景宁| 石渠县| 延寿县| 广西| 常山县| 银川市| 吴堡县| 乌兰察布市| 府谷县| 灵璧县| 赤城县| 武胜县| 息烽县| 逊克县| 上思县| 城市| 黄浦区| 庄浪县| 印江| 河北省| 房产| 宽城| 常宁市| 栖霞市|