4

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?

Taras
  • 32,823
  • 4
  • 66
  • 137
spreaderman
  • 101
  • 7

2 Answers2

3

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

Taras
  • 32,823
  • 4
  • 66
  • 137
Babel
  • 71,072
  • 14
  • 78
  • 208
2

Try this:

coalesce(
 aggregate(layer:='line99',
 aggregate:='sum',
 expression:=length($geometry),
 filter:=intersects( $geometry, geometry(@parent))),
0)

Aggregate: "Returns an aggregate value calculated using features from another layer."

The aggregate to calculate is sum, and the values to sum are the lengths of the lines intersecting @parent feature which is each polygon.

For the polygons that doesnt intersect any line the value will be NULL and coalesce is returning 0 for these features. enter image description here

BERA
  • 72,339
  • 13
  • 72
  • 161