2

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])
5

Firstly, for every feature, you have to create a new QgsFeature and set its geometry and then add 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)
|improve this answer|||||

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.