Search code examples
gispostgis

How to expand LineString centerline into a rectangular polygon in PostGIS?


I have a table containing LineString geometries (SRID=4326). Given that line, I also have a "left" and "right" value in miles for each row. They may not always be equal.

I want to produce a polygon from that LineString that is properly expanded on each side in miles to form a resulting rectangle.

I was trying to adapt this solution here so far without success: https://gis.stackexchange.com/questions/60655/polygon-to-fill-gap

I can generate two parallel lines with ST_OffsetCurve(), but haven't been able to create the polygon so far. Thanks a lot for any suggestions!


Solution

  • You can create a minimum bounding rectangle for your linestring geometry. The function in postgis you can use is ST_Envelope. See https://postgis.net/docs/ST_Envelope.html for some examples. If you have this rectangle, you can expand it with your given left and right values. See function ST_Expand https://postgis.net/docs/ST_Expand.html

    Updated my answer (according to the screenshots): You can do the following steps to create your desired geometry in postgis.

    drop table linetest;
    --create table to test
    create table linetest (
        id serial not null,
        geom geometry,
        parallel_geom geometry,
        union_lines geometry,
        polygon_geom geometry   
    );
    --insert sample linestring
    insert into linetest (geom) values (
        ST_GeomfromEWKT('SRID=4326; LINESTRING(100 100, 200 200)')
    );
    --create parallel linestring (query your field dx or dy for the parallel value here)
    update linetest set parallel_geom = (
        select ST_OffsetCurve(geom,
        -15, -- here you can parametrize your offset
        'quad_segs=4 join=round')
    );
    --union the 2 lines to get one geometry as a multilinestring
    update linetest set union_lines = (
        select ST_Union(geom, parallel_geom)
    );
    --create polygon with function convex hull out of the multilinestring
    update linetest set polygon_geom = (
        select ST_ConvexHull(union_lines)
    );
    --check your result
    select ST_ASTEXT (polygon_geom) from linetest;
    

    I visualized the situation in qgis, see image: Convex Hull