QGIS Field Calculator – Adding Up Line Length for Lines That Pass Through Polygon

field-calculatorlengthlineoverlapping-featuresqgis

I have three lines as per the below picture. The layer is called 'line'. A is 60m, B is 30m and C is 90m. I have a polygon layer consisting of 1 square. The layer is called 'polygon'.

I want to make a calculated field called "ttl_length" in the polygon layer which is the total length of all lines that pass through the polygon. In other words, the total should be 180m.

enter image description here

I am currently using the below-calculated field:

aggregate(layer:='line',
      aggregate:='sum',
      expression:= "line_length" ,
      filter:=intersects(geometry(@parent), $geometry) 
      )

The above will only give me the sum of the length of lines actually inside the square. I need the length of all the lines (eg. 180m). How can I do that?

Best Answer

An easier way to achieve that is to use overlay_intersects() to create an array of the lengths of all intersecting lines, then calculate the sum with array_sum():

array_sum (overlay_intersects ('line', length($geometry)))

To calculate ellipsoidal length, you could also use $length instead of length($geometry).

Related Question