2

I am developing a plugin in QGIS using PyQt5. I have used the following code to create a buffer of different distance for different features in a layer.

layers = [layer for layer in QgsProject.instance().mapLayers().values()]
drainIndex = self.dlg.comboBox_4.currentIndex()
drain = layers[drainIndex]
path=os.path.dirname(unicode(drain.dataProvider().dataSourceUri()))
crs=drain.crs()
outLayer = QgsVectorLayer(path,'Buffer1',"ogr")
out=os.path.join(path,'Buffer1.shp')
prov = outLayer.dataProvider()
outLayer.startEditing()
   for feat in drain.getFeatures():
        inAttr = feat.attributes() # Input attributes
        inGeom = feat.geometry() # Input geometry
        Segments=20
        bf_inGeom = inGeom.buffer(feat['B1'], Segments)
        poly=bf_inGeom.asPolygon()
        outGeom = QgsFeature()
        outGeom.setGeometry(QgsGeometry.fromPolygonXY(poly)) # Output geometry
        outGeom.setAttributes(inAttr) # Output attributes
        prov.addFeatures([outGeom])
        QgsVectorFileWriter.writeAsVectorFormat(outLayer,out,'utf-8',destCRS=crs,driverName='ESRI Shapefile')
    outLayer.commitChanges()

It is generating buffer correctly around the polygon, which is an input. But also it gives some extra features which are the buffers on the input polygon.

Therefore it is giving double features than expected. One is the buffer outside input polygon and another is buffer on the input polygon. It is shown on the image given below.

Example

As shown on the picture green coloured polygon is an input file. Red lines are buffers. I want buffer which is outside of input file.

What changes are recommended in the code?

1

Here, I still could not find out that why buffer is giving inappropriate output. As i had mentioned it is creating a different buffer on the input file and also creating buffer of given distance. To solve my problem I had to delete features from output layer by comparing geometries. If anyone faces the same problem, one can use this trick.

prov.addFeatures([outGeom])
for f in outLayer.getFeatures():
     if feat.geometry().equals(f.geometry()):
         prov.deleteFeatures([f.id()])
         QgsVectorFileWriter.writeAsVectorFormat(outLayer,out,'utf-8',destCRS=crs,driverName='ESRI Shapefile')
         outLayer.updateFeature(f)

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.