- QGIS Python Programming Cookbook
- Joel Lawhead
- 286字
- 2021-07-23 19:48:56
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:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, load the layer and validate it:
vectorLyr = QgsVectorLayer('/qgis_data/polygon/polygon.shp', 'Polygon' , "ogr") vectorLyr.isValid()
- Next, access the layer's data provider:
vpr = vectorLyr.dataProvider()
- 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))
- 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])
- Next, build the feature object and add the points:
f = QgsFeature() f.setGeometry(poly)
- 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.
- Modular Programming with Python
- PostgreSQL for Data Architects
- 信息可視化的藝術:信息可視化在英國
- Scratch真好玩:教小孩學編程
- 數據結構(C語言)
- 表哥的Access入門:以Excel視角快速學習數據庫開發(第2版)
- Java程序設計
- UVM實戰
- RocketMQ實戰與原理解析
- Scala編程實戰
- Mastering VMware Horizon 7(Second Edition)
- Python機器學習與量化投資
- Java高手是怎樣煉成的:原理、方法與實踐
- HTML5游戲開發實戰
- Laravel Design Patterns and Best Practices