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.
- Name field too long.
- You don't need index name field as parameter. You need attribute value.
- 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"):
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:
and it works as expected.
No comments:
Post a Comment