QGIS – Joining Attributes from Points to Lines Using Spatial Join

attribute-joinsqgisspatial-join

I am working with two shapefile layers: lines and points. These shapefiles do not overlap and have different attribute values.

example

The point layer contains data that I want to join to the beginning and end of the line layer. If a canĀ“t join this data by field value or location, which vector tool should I use in QGIS?

Best Answer

I have tried to set up the example above. I hope I correctly noticed that your point layer consists of points located very close to each other. Looks like the output after using the 'Create points along lines' tool.


I can suggest using a "Virtual Layer" through Layer > Add Layer > Add/Edit Virtual Layer....

Let's assume we have the following layers 'Layer_Points' and 'Layer_Lines', see image below. The data that has to be transferred from the points placed in the field "Data".

input

With the following query, it is possible to join points' attributes to lines appropriated through the beginning and the end of the line layer.

WITH start_points AS (
    SELECT
        l.id,
        p."data"
    FROM
        "Layer_Lines" AS l,
        "Layer_Points" AS p
    GROUP BY
        l.id
    ORDER BY
        MIN(ST_Length(ST_ShortestLine(start_point(l.geometry), p.geometry))) DESC
    ),

end_points AS (
    SELECT
        l.id,
        p."data"
    FROM
        "Layer_Lines" AS l,
        "Layer_Points" AS p
    GROUP BY
        l.id
    ORDER BY
        MIN(ST_Length(ST_ShortestLine(end_point(l.geometry), p.geometry))) DESC
    )

SELECT
    l.*,
    sp."data" AS "start_data",
    ep."data" AS "end_data"
FROM
    "Layer_Lines" AS l
JOIN start_points AS sp
    ON sp.id = l.id
JOIN end_points AS ep
    ON ep.id = l.id

The output Virtual Layer with its Attribute table will look as following

output


ST_ShortestLine()is the shortest line between two geometries. ST_StartPoint() defines the lines' starting points for connecting with points layer, see image below.

start_point

The same principle was applied for ST_EndPoint()

Related Question