Friday 26 October 2018

postgis - PostgreSQL create line from points


How do i create a linestring from points sort by date in PostgreSQL?


I tried:


SELECT observations.id,

ST_MakeLine(observations.geom ORDER BY observations.date) AS newgeom
FROM observations
GROUP BY
observations.id;

This is going wrong. It returns me a linestring with same coordinates. So, instead of a line from a to b, it gives me a to a.


enter image description here


What am I doing wrong?



Answer



The point is, if you GROUP BY the row id column, you will get one result row per input row (this is equal to grouping by the actual date column)! And since a Linestring is only valid with a minimum of two points, ST_MakeLine adds the same point twice.



Either run


SELECT ST_MakeLine(geom ORDER BY date) AS geom
FROM observations
;

to get one line for all points, or


SELECT ROW_NUMBER() OVER() AS id,
*
FROM (
SELECT ST_MakeLine(geom, LEAD(geom) OVER(ORDER BY date)) AS geom

FROM observations
) q
WHERE geom IS NOT NULL
;

to get a linestring between each pair of consecutive points.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...