3

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

Vince
  • 20,017
  • 15
  • 45
  • 64
Luigi Falco
  • 131
  • 9

1 Answers1

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

geozelot
  • 30,050
  • 4
  • 32
  • 56