QGIS – How to Create Lines from Points and Transfer Attributes to Line Segments

geometry-by-expressionpoints-to-lineqgis

Background:

I need to create lines from points where the point attributes are transferred to the line segments.

The screenshot below shows two point tracks. Each track's point has a unique id and an additional attribute, in this case elevation.

enter image description here

Here's a screenshot showing the point layer's attribute table:

enter image description here

Below is a screen shot showing the desired line output. Notice that each line segment now contains both of the elevation values from the two points that comprised that line segment.

enter image description here

The resulting line attribute table includes three new fields: line_segment, elevation_begin, and elevation_end.

enter image description here

Question:

I don't know how to create new lines that contain attribute values from the source points. None of the "point to line" tools or plugins offer this functionality. There used to be a plugin named "Points2Paths" that could do this, but it has been removed from the repository.

I suppose that Geometry by Expression might offer a solution, but I don't know where to begin…

Best Answer

I imagine you're right that Geometry by Expression could be used but my brain reflexively thinks of an SQL solution:

Layer|Create Layer|New Virtual Layer...

enter image description here use the following for the SQL, substituting "point_track" with the name of your point layer

SELECT p1.track,p1.id AS line_segment,p1.elevation AS elevation_begin,p2.elevation AS elevation_end, make_line(p1.geometry,p2.geometry) AS geom 
FROM point_track p1 
JOIN point_track p2 ON p2.track=p1.track AND p2.id=p1.id+1

enter image description here

Edit: As Stu pointed out (and I neglected to mention) this query assumes sequential integer type id numbers. I think its a quirk of the SQLite engine that it also works when the numbers are in a text field. Rather than complicating the SQL, if you do happen to have non sequential ids (or text ids like a, b, c..) the simplest approach might be to use the Processing Toolbox "Add autoincrement field":

  • Group values by "track".
  • If you have numeric ids in a text field use Sort expression to_int("id")
  • otherwise just sort by "id"

Then adjust the query to use the newly generated sequential id field: enter image description here

Related Question