- QGIS Python Programming Cookbook
- Joel Lawhead
- 358字
- 2021-07-23 19:48:56
Adding a set of attributes to a vector layer
Each QGIS feature has two parts, the geometry and the attributes. In this recipe, we'll add an attribute for a layer from an existing dataset.
Getting ready
We will use a point shapefile with museum data for New York City, which you can download as a ZIP file from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Extract this shapefile to the /qgis_data/nyc
directory.
How to do it...
A feature must have geometry, but it does not require attributes. So, we will create a new feature, add some attributes, and then add everything to the layer, as follows:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, load the layer and validate it:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
- Next, access the layer's data provider so that we can get the list of fields:
vpr = vectorLyr.dataProvider()
- Now, create a point geometry, which in this case is a new museum:
pnt = QgsGeometry.fromPoint(QgsPoint(-74.13401,40.62148))
- Next, get the
fields
object for the layer that we'll need to create a new feature for:fields = vpr.fields()
- Then, create a new feature and initialize the attributes:
f = QgsFeature(fields)
- Now, set the geometry of our new museum feature:
f.setGeometry(pnt)
- Now, we are able to add a new attribute. Adding an attribute is similar to updating a Python dictionary, as shown here:
f['NAME'] = 'Python Museum'
- Finally, we add the feature to the layer and update the extents:
vpr.addFeatures([f]) vectorLyr.updateExtents()
How it works...
PyQGIS attributes are defined as an ordered array
. The syntax for referencing a field is similar to the syntax for a Python dictionary. We use the layer's data provider object to perform the actual editing. When we use this approach, no signals are triggered at the layer object level. If we are just trying to edit data on the filesystem, that's okay, but if the layer is going to be added to the map canvas for display or user interaction, then you should use the editing buffer in the QgsVectorLayer
object. This editing buffer allows you to commit or roll back changes and also keeps track of the state of the layer when things are changed.
- PHP動(dòng)態(tài)網(wǎng)站程序設(shè)計(jì)
- Spring 5.0 Microservices(Second Edition)
- Java加密與解密的藝術(shù)(第2版)
- Java程序員面試算法寶典
- PostgreSQL 11從入門到精通(視頻教學(xué)版)
- Nginx實(shí)戰(zhàn):基于Lua語言的配置、開發(fā)與架構(gòu)詳解
- Learning Unreal Engine Android Game Development
- Learning jQuery(Fourth Edition)
- 創(chuàng)意UI:Photoshop玩轉(zhuǎn)APP設(shè)計(jì)
- 例解Python:Python編程快速入門踐行指南
- Responsive Web Design with jQuery
- 數(shù)據(jù)結(jié)構(gòu)與算法詳解
- 劍指大數(shù)據(jù):企業(yè)級(jí)電商數(shù)據(jù)倉庫項(xiàng)目實(shí)戰(zhàn)(精華版)
- Visual FoxPro數(shù)據(jù)庫程序設(shè)計(jì)
- 51單片機(jī)C語言程序設(shè)計(jì)經(jīng)典實(shí)例(第3版)