9

I found this article which describes the "QGIS GUI way" for calculating the line lengths http://www.qgistutorials.com/en/docs/calculating_line_lengths.html

How can I calculate the length of one line (feature) in a vector layer with Python code?

As an example, I want to know the length of the yellow line.

enter image description here

17

From the QGIS Documents: Geometry Handling, you can use the following code to get the length of any selected line(s):

layer = qgis.utils.iface.activeLayer()
features = layer.selectedFeatures()
for f in features:
    geom = f.geometry()
    print "Length:", geom.length()
4
  • @Joseph, how can I tweak it so that it calculates it for all atrributes in all layers in a project rather than just the selected ones? I have experimented a little but my code isn't doing the trick: layer = layer in QgsMapLayerRegistry.instance().mapLayers().values() features = layer.allFeatures() for f in features: geom = f.geometry() print "Length:", geom.length() – Hannes Ledegen Jan 5 '17 at 10:19
  • 1
    @HannesLedegen - You're close! Try for layer in QgsMapLayerRegistry.instance().mapLayers().values(): features = layer.getFeatures() for f in features:... – Joseph Jan 5 '17 at 10:48
  • @Joseph I have clarified a little in my answer below for saving it to an attribute rather than displaying it. I feel like there is mainly an indention problem still but I must say I am not so goot with python. – Hannes Ledegen Jan 5 '17 at 11:09
  • @HannesLedegen - I think everything after line 2 should be indented. – Joseph Jan 5 '17 at 11:11
3

Great code, however, this only works for the selected layer and only prints it. With some help from other posts and @Joseph I turned it into a code that adds an attribute to all layers in your project with the length.

from PyQt4.QtCore import QVariant

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    features = layer.getFeatures()
    
    for f in features:
    geom = f.geometry()
    leng = geom.length()
    res = layer.dataProvider().addAttributes([QgsField("Length", QVariant.Int)])
    layer.updateFields()
    fieldIndex = layer.dataProvider().fieldNameIndex("Length")
    attrFeatMap = {}
    attrMap = {fieldIndex: leng}
    
    for feature in layer.getFeatures():
        attrFeatMap[feature.id()] = attrMap
    
    layer.dataProvider().changeAttributeValues(attrFeatMap)

Not the answer you're looking for? Browse other questions tagged or ask your own question.