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

14

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()

Hope this helps!

  • 1
    Beated by seconds... :-) – Alexandre Neto Nov 3 '15 at 14:57
  • @AlexandreNeto - Haha sorry! Was sheer coincidence because I was also using this exact code for my layers only moments ago :) – Joseph Nov 3 '15 at 15:00
  • @gustavgans - Most welcome buddy :) – Joseph Nov 3 '15 at 15:01
  • @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
1

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 )

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.