3

I'm trying to create a new layer, in which the buffers are displayed. I tried this code, but it does not work. Where is the error?

layer = iface.activeLayer()
buff_layer = QgsVectorLayer("Polygon?crs=epsg:4326","buffer", "memory")
bufferDist = 10

for feat in layer.getFeatures():
  geom = feat.geometry()
  buff = geom.buffer(bufferDist,5)
  feat.setGeometry(buff)
  buff_layer.addFeature(feat)   

QgsProject.instance().addMapLayers([buff_layer])
0

1 Answer 1

6

Firstly, for every feature, you have to create a new QgsFeature and set its geometry and then add it to the layer.

Solution 1: Edit Session

layer = iface.activeLayer()
buff_layer = QgsVectorLayer("Polygon?crs=epsg:4326", "buffer", "memory")
bufferDist = 10

# start edit session
buff_layer.startEditing()
for feat in layer.getFeatures():
  geom = feat.geometry()
  buff = geom.buffer(bufferDist, 5)

  # create a new empty feature
  f = QgsFeature()
  f.setGeometry(buff)
  buff_layer.addFeature(f)

# commit changes to the layer
buff_layer.commitChanges()

QgsProject.instance().addMapLayer(buff_layer)

Solution 2: Using Data Provider

layer = iface.activeLayer()
buff_layer = QgsVectorLayer("Polygon?crs=epsg:4326", "buffer", "memory")
bufferDist = 10

for feat in layer.getFeatures():
  geom = feat.geometry()
  buff = geom.buffer(bufferDist, 5)

  # create a new empty feature
  f = QgsFeature()
  f.setGeometry(buff)

  ### 
  buff_layer.dataProvider().addFeatures([f])
  ###

QgsProject.instance().addMapLayer(buff_layer)
1
  • 1
    Solution 2 is more clear. Commented Feb 21, 2020 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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