4

I've been through some of the examples and solutions posted here for calculating chainage of a line or cumulative values. However, I am still unable to achieve the desired outcome.

What I am trying to do is to add the "Length" values by "row number". So the "Chg"(Chainage) i.e. a cumulative value of line section 1 = 7.69026, 2 = 14.83986, 3 = 22.69265 ... etc. Is there an expression I can use in field calculator to achieve this?

enter image description here

1

2 Answers 2

6

+1 for the custom function, they are a good trick to have up your sleeve.

In this case you can do it with the built-in aggregate()function:

aggregate('Line_CHain', 'sum', "Length", "id"<=attribute(@parent, 'id'))
1
  • Thank you M Bain that worked a treat. Nice one! Thanks also Louis Cottereau. I didn't try the script but will at some point. Cheers
    – JohnF
    Aug 30, 2020 at 23:43
6

In your Field Calculator, go into the Function Editor, create a new file, insert this function:

"""
Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments
"""

from qgis.core import *
from qgis.gui import *
import sys
if sys.version_info.major == 3:
    layer_registry = QgsProject
else:
    layer_registry = QgsMapLayerRegistry

@qgsfunction(args="auto", group='Custom')
def get_length_feature(layer_id, feature, parent):
    id = feature.id()
    len_tot = 0.
    for feat in layer_registry.instance().mapLayer(layer_id).getFeatures():
        if feat["id"] <= feature["id"]:
            len_tot += feat.geometry().length()
    return len_tot

Load it, return into the expression tab and insert the following: get_length_feature(@layer_id)

2
  • 1
    This will for each segment add all prevoius segments. That may not be a concern when your line has fewer than (say) a million segments, but runtime will grow exponentially (as far as i can math ;) ).
    – til_b
    Aug 28, 2020 at 12:23
  • 1
    True, so would the other answer also. However in that case i would definitely not do it like this, and i wouldn't use a million independant features also to do an incremental distance calcul. In that case i would do it programmaticaly with a single feature containing all the points as either a linestring or multilinestring Aug 28, 2020 at 12:29

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.