3

I started studying the examples provided in the "QGIS Python Programming cookbook".

I downloaded the point vector layer as example from https://code.google.com/archive/p/geospatialpython/downloads?page=2 and uploaded in QGIS.

The code below should append a point to the existing points of the vector layer:

vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums', "ogr")
vpr = vectorLyr.dataProvider()
pnt = QgsGeometry.fromPoint(QgsPoint(-74.80,40.549))
f = QgsFeature()
f.setGeometry(pnt)
vpr.addFeatures([f])
vectorLyr.updateExtents()

But, at the end, any new points has been added. May you help me?

  • You have one error an one omission (please see my answer). – xunilk Apr 1 '17 at 4:20
3

You have one error an one omission. Your relative path (if your home path is /home/user_name/; because I believe that you use Linux) should be:

'qgis_data/nyc/NYC_MUSEUMS_GEO.shp'

and you need to add this QgsVectorLayer to registry.

Next code should work perfectly:

vectorLyr = QgsVectorLayer('pyqgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums', "ogr")
n_features = vectorLyr.featureCount() #added line
vpr = vectorLyr.dataProvider()
pnt = QgsGeometry.fromPoint(QgsPoint(-74.80,40.549))
f = QgsFeature()
f.setGeometry(pnt)
f.setAttributes([n_features]) #added line
vpr.addFeatures([f])
vectorLyr.updateExtents()

QgsMapLayerRegistry.instance().addMapLayer(vectorLyr) #added line

as you can see at next image:

enter image description here

Isolate point is added QgsPoint.

Note: If you have some problem with relative path use absolute path. On the other hand, if you want to include FID value of this feature you need two additional lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.