Mastering PostGIS
上QQ阅读APP看书,第一时间看更新

LineString composition

The rules for composing LineStrings are similar to those governing MultiPoint composition: Two points, an array of points, or a set of aggregated rows can be supplied. The PostGIS function designed for creating LineStrings is called ST_MakeLine. Point geometries required for composition can be already stored in a table, or created from raw coordinates using the ST_MakePoint function.

The following example will create a straight line connecting two points:

SELECT ST_MakeLine(ST_MakePoint(20,50),ST_MakePoint(19.95,49.98)); 

When using raw coordinates, the output geometry will have an unknown SRID, so the complete example will be as follows:

SELECT ST_SetSRID(ST_MakeLine(ST_MakePoint(20,50),ST_MakePoint(19.95,49.98)),4326);  

For three or more points and raw coordinates, the ARRAY argument can be used:

SELECT ST_MakeLine(ARRAY[ST_MakePoint(20,50),ST_MakePoint(19.95,49.98), ST_MakePoint(19.90,49.96)]);  

And finally, the aggregate variant. This is especially useful when dealing with a series of points from GPS tracking devices:

SELECT ST_MakeLine(gpx.geom ORDER BY time) AS geom
FROM gpx
GROUP BY 1;
A set of GPS measurement points.

The image we just saw contains a visualization of discrete GPS points. Each one has a time attribute that can be used for sorting, so a LineString can be composed without issues.

In the next step, the sorted points are composed into a single geometry of the LineString type:

A LineString created from a set of points.

The GROUP BY 1 is used to aggregate all rows in a table (if a table consists of multiple tracks and they have a unique ID, a real column with this ID should be used instead), and the ORDER BY timestamp clause ensures the correct order of points to create a valid line.