How can I select a line having the centroid inside a polygon? there is a specific fuction?
1 Answer
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 linesSELECT 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 wantST_PointOnSurface
is extended in PostGIS to work on arbitrary geometries and guarantees[*] a point on the line around the geometric center using a deterministic algorithmST_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