I used the following code to add a separate column to the attribute table with the length of features.

from PyQt4.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature
myField = QgsField( 'myattr', QVariant.Int )
vl.addAttribute( myField )
idx = vl.fieldNameIndex( 'myattr' )
e = QgsExpression( '$length' )
e.prepare( vl.pendingFields() )
for f in vl.getFeatures():
    f[idx] = e.evaluate( f )
    vl.updateFeature( f )

But sometimes it will add a new column and show 0 or NULL in each row, and sometimes it shows the length of feature in degrees.

What did I do wrong?

And is there any way to add length in meters without changing the project CRS?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.