# Calculating mean slope of lines based on DEM?

I have a DEM and a line vector shapefile (also available in PostGIS) and I need to calculate the mean slope of every line. Direction of the slope (positive or negative) is not important.

That means I should assign the DEM raster values of the start and end vertex to two new attributes (e.g. alti_a and alti_b). Then it would be possible to use field calculator and calculate the slope.

How can I do this? Are there alternative solutions?

• are you willing to move to PostGIS completely, including the upload of your DEM to the DB (mind you, this might be a little time intensive, depending on the DEM's size and/or if you're not familiar)? there are options in QGIS, but once imported in PostGIS you could do that in one query and easily repeat it if necessary. Feb 6, 2018 at 12:01
• @ThingumaBob I am...but I'm new to PostGIS and it took me quite a while to install the server...so I assume I'd need to follow this [RastertoPostGIS] (gis.stackexchange.com/questions/58619/…) and then this [ExtractElevationValues] (gis.stackexchange.com/questions/129503/…) Feb 6, 2018 at 12:07
• btw: what do I do wrong with the mini-Markdown formatting for the links? Feb 6, 2018 at 12:10
• -> no space between ] and ( Feb 6, 2018 at 12:11
• thx. And am I right with the two links? Feb 6, 2018 at 12:24

Assuming you have DEM height (z) at both ends as `"z1"`, `"z2"` fields respectively in your line layer, try this expression in the Field Calculator.

``````degrees(atan2(abs("z2"-"z1"), sqrt((\$x_at(-1)-\$x_at(0))^2 + (\$y_at(-1)-\$y_at(0))^2)))
`````` • thx for your explanation! I understand the field calculator expression. But how can I create the z1 and z1 fields out of the DEM? Feb 7, 2018 at 11:30
• @Kevkev770 As you have z information through SAGA `Grid values to Point` tool, z values are stored in point layer. Join line and points together. To be honest I usually manually copy and paste z-values as I do not have too many lines. Feb 7, 2018 at 11:39
• do you know how I could determine which point is z1 and which one is z2? I have way too many points to do it manually. Feb 7, 2018 at 12:21
• @Kevkev770 Because of `abs()`, either will do. It is still better sticking to your own rule, just to avoid potential confusion (for future updates). Feb 7, 2018 at 12:25
• ok...I tried using Join attribute by location but then I only have one value Z-Value for each line. Would you mind telling me what tool I should use? Feb 7, 2018 at 13:19

To get the elevation / z values from the DEM for (all) the vertices of your line geometries, you can use the Drape (set Z value from raster) QGIS algorithm.

You can then use Extract specific vertices to get to the start (0) and end (-1) points of the lines.

(or you can extract the start and end points first and then get the z values from the DEM)

In your calculations you can then use the `z(geom)` function to get the `z` (elevation) values from the geometries.