Creating flat end buffer using geometry generator in QGIS?

In QGIS 3.2, there are additional buffer functions you can use to style your lines. Each function has a set of properties you could set such as the number of segments and, most importantly in your case, setting the join style (i.e. round, miter (flat) or bevel). These are not available in QGIS 2.x but if you can get access to the latest QGIS version, you could follow the steps below:


  1. At the moment, there is only the single_sided_buffer function which uses the join style property. This creates a buffer on either side of the line but we can use two of these and split the difference in width so that it will look like a single buffer. We can use an expression like:

    single_sided_buffer( geometry, distance, segments, join)
    

    where:

    • geometry - Current geometry
    • distance - Buffer distance (positive values = left of line; negative values = right of line)
    • segments - Number of segments used to represent circles. This is supposed to be optional but for some reason, I need to include it otherwise it won't work.
    • join - Join property (1 = round, 2 = miter and 3 = bevel)

  1. Add a symbol layer for the geometry generator and we will create one side of the buffer with an expression like:

    single_sided_buffer( $geometry, 0.05, 0, 2)
    

    Symbology


  1. Add another and use negative values:

    single_sided_buffer( $geometry, -0.05, 0, 2)
    

  1. This should give the appearence of a rectangular buffer (the red lines are the original line features):

    Buffer


You can create a virtual layer that transforms your line into a polygon. You would then style this new layer.

Go to layer / add layer / add - edit virtual layer and type the following query. Rename a by your line layer, and add fields as needed. 0.01 is the 1/2 buffer size (here in degrees) and the ending 0 / 1 is for right or left side.

You can at the same time compute the line azimuth (angle between the horizontal and the 1st/last point of the line, expressed in radians)

select id, 
 st_union(ST_SingleSidedBuffer(geometry,0.01,0) ,  ST_SingleSidedBuffer(geometry,0.01,1)),
 st_azimuth(st_startpoint(geometry),st_endpoint(geometry)) azim 
from a

enter image description here