1

I'm trying to calculate the road length for hundreds of layers, each one being a small road vector layer. I usually follow the process at

https://www.qgistutorials.com/en/docs/calculating_line_lengths.html

which is basically creating a new field in the Field Calculator, entering $length, and looking at the sum in Summary Statistics. Is there a way to rapidly do this for all layers so I get a list of layers and the length of each?

2
  • i'm sure the solution exists on this site already! You could generate a small python script to do this or use a model in QGIS to do in batch. For the python solution - it would involve a script that does the following: 1.) iterate over list of layers (or files in a directory!) 2.) add column/field 3.) populate the new column with $length
    – SaultDon
    Commented Aug 13, 2021 at 23:00
  • You might merge your layers, add the length field and calculate it. To get the total for each layer run a dissolve and recalculate the lengths. You can use the split vector tool on either to get individual layers back with the new information in each.
    – John
    Commented Aug 13, 2021 at 23:50

1 Answer 1

1

One solution amongst multiple possibilities. You need to select your layers and they need to be lines.

selected_layers = iface.layerTreeView().selectedLayers()

for layer in selected_layers:
    print(f"{layer.name()} : {sum([f.geometry().length() for f in layer.getFeatures()])}")

or to always get meters units by using ellipsoidal length (borrowed from Calculating elipsoidal length of line in PyQGIS)

import pandas as pd

selected_layers = iface.layerTreeView().selectedLayers()

d = QgsDistanceArea()
d.setEllipsoid('WGS84')

result = []
for layer in selected_layers:
    tot = 0
    for f in layer.getFeatures():
        m = d.measureLength(f.geometry())
        if m > 0:
            tot += m
    print(f"{layer.name()} : {tot}")
    result.append([{layer.name()}, f"{tot}"])

# To get a dataframe
df = pd.DataFrame(result, columns=['layer_name', 'tot'])
df.to_csv("your_layers_count.csv", index=False)

# For export to CSV without pandas deps, see https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file

2
  • How do I get this output? i.e. save as csv? I stored these values in a pandas dataframe
    – Ben Hendel
    Commented Aug 23, 2021 at 22:20
  • Edited my 2nd answer
    – ThomasG77
    Commented Aug 23, 2021 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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