How to calculate the road slope using plain QGIS

For my first blog in this platform I have decided to share the method that I use to calculate the slope for the different segments of a road network using QGIS. During this exercise, I will be using QGIS 3.8, a Digital Elevation Model (DEM) for my area of study and a road network in the form of an Esri shapefile.
The first step in the process that I follow usually involves the splitting of the network segments into shorter ones; however, in this example I will ignore that step to keep the blog entry short. After you have loaded your layers (DEM and network) in the map canvas in QGIS you have two options, you can either use the UI or you can use the Python console, for this example we will use the Python console.
Extract the Z values using the DEM
The process of calculating the slope for a road segment requires you to know the elevation for the different vertices in the geometry. To achieve this we make use of two different built-in algorithms, the “Drape (set Z value from raster)” and “Extract Z values”.

Calculate the road slope
After the subsetting of the Z values for the different vertices, we proceed to generate a new field with the value for the slope. In the example presented below, we make use of a field called length that represents the length of each segment, if you split the segment of the network this is a field that requires to be recalculated using the field calculator and the function ‘$length’.

Now you should be able to produce something similar to the image in the cover of this blog entry. Cheers
