I have one polygon layer "polygons" and one line layer "lines". I would like to create a layer with all line parts that are inside the polygon layer. First I cut the lines in the intersection of the polygon layer. I can see that all lines are cut in the intersection of the polygons. then I would like to select the line parts inside the polygon that has a length longer than approximate the double width of the polygon (buffer). First image shows the cutted lines, I've highlighted one line for you to see. the black area is the polygons (buffer).

cutted lines in the black polygon, one highlighted

I use the following sql to select the "inside"-lines:

CREATE TABLE public."insidelines" AS SELECT l.*
    FROM "lines" l
        LEFT JOIN "polygons" p ON ST_Contains(p.the_geom, l.the_geom)
    WHERE p.the_geom IS NOT NULL AND ST_Length(l.the_geom) > 2000;

 ALTER TABLE public."insidelines" ALTER COLUMN the_geom TYPE geometry(LINESTRING, 32633) USING ST_SetSRID(the_geom, 32633);

the result is:


It is only the yellow line that was found! Any idea why?

Both layers are in UTM 33 (32633). I'm using PostGIS ver 2.5

  • contains in this case is wrong, because the line geometry is NOT completely (somehow and somewhere) contained into the polygon one. You can try touches or within instead
    – Taras
    May 26, 2021 at 9:27
  • It is the same result with st_within, st_touches will find any line outside or inside that touches the polygon/polygon border.
    – Paul
    May 26, 2021 at 9:35
  • Please check this for more details: gis.stackexchange.com/questions/217444/…
    – Taras
    May 26, 2021 at 12:42
  • 1
    Ah, I see, the cutting is likely the issue then (due to rounding, grid snapping, the point is not exactly on the polygon border). You can try adding a vertex to the polygon at the intersection point + do a snapToGrid on both the cut lines and the polygons after the cut. Alternatively, it may be (much) simpler to just select lines whose center point is within the polygons, or to apply a very small buffer to the black polygons
    – JGH
    May 26, 2021 at 14:28
  • 1
    Centerpoint! Clever!
    – Paul
    May 26, 2021 at 15:13


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.