3

I'm developing a script in processing for personal use and have some difficulties with the Qgis API. I bought The Pygis Programmers guide . It has been useful but I have had some difficulties in defining processes. I just want to create a script that writes me the same shapefile , add two fields and then calculate the ratio perimeter area.

This is my code:

##testes=group
##Ratio =name
##layer=vector
##output_file=output vector

from PyQt4.QtCore import QVariant
from qgis.core import QGis, QgsFeature, QgsField, QgsFields
from processing.tools.vector import VectorWriter

vectorLayer = processing.getObject(layer)

provider = vectorLayer.dataProvider()

writer = VectorWriter(output, None, provider.fields(),
                  provider.geometryType(), vectorLayer.crs())

features = processing.features(vectorLayer)
for feat in features:
writer.addFeature(feat)

del writer

#add fields 
New_layer= processing.getObject(layer)
fields=QgsFields()
fields.append(QgsField('AREA', QVariant.Double,'',20,3))
fields.append(QgsField('PERIMETER', QVariant.Double,'',20,3))
fields.append(QgsField('RATIO', QVariant.Double,'',20,3)) #Perimeter/Area   (RATIO)
writer = processing.VectorWriter(output_file, None, fields.toList(),
                              QGis.WKBMultiPolygon, New_layer.crs())
del writer
2

I don't think you need two instances of writer so you can remove the first one. I've modified your code so that the output takes the fields of the input and adds the new fields you defined:

##testes=group
##Ratio =name
##layer=vector
##output_file=output vector

from PyQt4.QtCore import QVariant
from qgis.core import QGis, QgsFeature, QgsField, QgsFields
from processing.tools.vector import VectorWriter

vectorLayer = processing.getObject(layer)
provider = vectorLayer.dataProvider()

New_layer= processing.getObject(layer)
fields = QgsFields()
fields = provider.fields()
fields.append(QgsField('AREA', QVariant.Double,'',20,3))
fields.append(QgsField('PERIMETER', QVariant.Double,'',20,3))
fields.append(QgsField('RATIO', QVariant.Double,'',20,3))

writer = processing.VectorWriter(output_file, None, fields.toList(),
                              QGis.WKBMultiPolygon, New_layer.crs())

features = processing.features(vectorLayer)
for feat in features:
    writer.addFeature(feat)

del writer

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.