3

How can I select a line having the centroid inside a polygon? there is a specific fuction?

1

1 Answer 1

4

You want a standard ST_Intersects filter, and then you have three options:

  • use the ST_Centroid to get the (weighted) centroid of the lines:
    SELECT ln.*
    FROM   <lines> AS ln
    JOIN   <polygons> AS pl
      ON   ST_Intersects(pl.geom, ST_Centroid(ln.geom))
    ;
    
  • use the ST_PointOnSurface to get a (non-weighted) center point of the lines
  SELECT ln.*
  FROM   <lines> AS ln
  JOIN   <polygons> AS pl
    ON   ST_Intersects(pl.geom, ST_PointOnSurface(ln.geom))
  ;
  • use the interpolated midpoint (ST_LineInterpolatePoint) of the lines
    SELECT ln.*
    FROM   <lines> AS ln
    JOIN   <polygons> AS pl
      ON   ST_Intersects(pl.geom, ST_LineInterpolatePoint(ln.geom, 0.5))
    ;
    

Depending on your lines, all three may differ:

  • ST_Centroid results in a point not guaranteed to be on the line (check the example in the docs) and is likely not what you want
  • ST_PointOnSurface is extended in PostGIS to work on arbitrary geometries and guarantees[*] a point on the line around the geometric center using a deterministic algorithm
  • ST_LineInterpolatePoint generates a point on the line at the given fraction of line length (0.5 for the midpoint) and guarantees[*] a point on the line

[*] within the margin of floating point rounding errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.