Getting total length of selected lines in QGIS via python


The other day I was trying to get the total length of the some selected lines in QGIS. In MapInfo I would just do

Select Sum(ObjectLen(obj,”m”)) from Selection

however QGIS doesn’t have the ability (yet..) to run SQL queries like this, but you can do it via python.

The following is a little python snippet that will get the total length of the selected objects. (You will need to have shapely installed to use)

from shapely.wkb import loads
def getLength():
    layer = qgis.utils.iface.mapCanvas().currentLayer()
    total = 0
    for feature in layer.selectedFeatures():
        geom = feature.geometry()
        wkb = geom.asWkb()
        line = loads(wkb)
        total = total + line.length
    return total

print getLength()

EDIT:Or as Peter asked in the comments, yes you can just call length on the geometry:

def getLength():
    layer = qgis.utils.iface.mapCanvas().currentLayer()
    total = 0
    for feature in layer.selectedFeatures():
        geom = feature.geometry()
        total = total + geom.length()
    return total

print getLength()

Just copy and past that into your QGIS python console and call getLength() when ever you need the total length.

Note: I have found the QgsGeometry .legnth() function to be unstable in the past and it has crashed my QGIS instance. Just test it first, if not you can always use the shapely method.

2 thoughts on “Getting total length of selected lines in QGIS via python

  1. Hi Nathan,
    So QGIS doesn’t have a nice SQL engine like MapInfo Pro? Well, I guess the SQL engine of MI Pro also really is one of the powerful sides of MI Pro.
    I also noticed that you need to go thru three steps to get to the line. Can’t you get the length directly from the geometry?

    PS: Knowing you, I’m sure it won’t be long before QGIS has a nice MapInfo Pro like SQL Engine ;-)

    1. Yeah it doesn’t really have the SQL engine like MapInfo, that is one thing I still like from MapInfo. QGIS uses OGR to open vector formats and OGR does support custom SQL however QGIS always just does a SELECT * FROM Datasource, although you can add a WHERE if needed.

      Yes the geometry object does have a length function and I could have done geom.length() but for some reason it was unstable in python last time I tried to use it. It only seems unstable in Python and not C++ so I think it has something to do with the Python garbage collection and bindings. I really need to fill a bug report.

      Yeah I do plan on adding something like what MI has it if I ever get the time, although I could just throw it out to the dev list and see if anyone else wants to take it on. The potential is there just need to find the time and get the C++ skills :)

Leave a comment