Monday, 26 March 2018

How to create dissolved buffer layer with pyqgis?


I have a line vector layer with a field name of "buffer_distance". I want create a dissolved buffer layer based on it's field. I write below code:


from qgis.utils import iface
from qgis.analysis import QgsGeometryAnalyzer
mc = iface.mapCanvas()
layer = mc.currentLayer()
Distance_Field = layer.fieldNameIndex("buffer_distance")
QgsGeometryAnalyzer().buffer(layer, "/tmp/buffer.shp", False, True, Distance_Field)


when run this code in QGIS 2.18 python console, It creates a new shapefile with all table fields of input layer but there is not any feature. What is problem?



Answer



You have several issues in your code.



  1. Name field too long.

  2. You don't need index name field as parameter. You need attribute value.

  3. Wrong parameters number and wrong order.


So, following code works as expected:


from qgis.utils import iface

from qgis.analysis import QgsGeometryAnalyzer
mc = iface.mapCanvas()
layer = mc.currentLayer()
feat = layer.getFeatures().next()
att = feat.attribute('buf_dist')

QgsGeometryAnalyzer().buffer(layer,
"/tmp/buffer.shp",
att,
False,

False,
-1)

After running it at Python Console of QGIS, I got desired buffer (retrieved from "/tmp/buffer.shp"):


enter image description here


as it can see at above image.


Editing Note:


In this case I would use QgsGeometry class because it also has a buffer method. Following code does the work:


mc = iface.mapCanvas() 
layer = mc.currentLayer()

feats = [ feat for feat in layer.getFeatures() ]

buffers = [ feat.geometry().buffer(feat.attribute('buf_dist'), -1).exportToWkt()
for feat in feats ]

epsg = layer.crs().postgisSrid()

uri = "Polygon?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes"

mem_layer = QgsVectorLayer(uri,

'buffers',
'memory')

prov = mem_layer.dataProvider()

feats = [ QgsFeature() for i in range(len(buffers)) ]

for i, feat in enumerate(feats):
feat.setAttributes([i])
feat.setGeometry(QgsGeometry.fromWkt(buffers[i]))


prov.addFeatures(feats)

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

I tried it out with line layer of following image:


enter image description here


and it works as expected.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...