liv a
liv a

Reputation: 3350

POSTGIS: find all the points within a polygon

I have a table containing point

CREATE TABLE Points
{
  pointID BIGSERIAL PRIMARY KEY NOT NULL,
  thePoint GEOGRAPHY(POINT)
}

CREATE TABLE Polygons
{
  polygonID BIGSERIAL PRIMARY KEY NOT NULL,
  aPolygon GEOGRAPHY(POLYGON) NOT NULL,
}

I wish to find all the points that are contained in each polygon. i.e the result should look like

polygonID| pointID
-------------------
1        | 1
1        | 2
1        | 5
1        | 7
2        | 2
2        | 3
...

I managed to go point by point and to figure out if it's in the polygon using ST_CoveredBy(thePoint, aPolygon). Based on that the naive solution is going in a nested loop over all points and polygons but for sure there is a more efficient and correct way to achieve this.

Upvotes: 2

Views: 6776

Answers (4)

Mike T
Mike T

Reputation: 43722

The answer was sort-of in your question: "within". Use the ST_DWithin operator.

SELECT polygonID, pointID
FROM Points
JOIN Polygons ON ST_DWithin(Points.thePoint, polygons.aPolygon, 0);

The last argument 0 is the distance within the polygon. This is useful to also select points that are, for example, within 10 m of the polygon, which is useful if there are positioning errors in the source data.

ST_Intersects(Points.thePoint, polygons.aPolygon) should also work.

See DE-9IM if you want to learn more on what these operators mean, but not all have geography type equivalents.

Upvotes: 1

mlinth
mlinth

Reputation: 3118

Here's one way, which works on geography types. BTW, might be worth reading the manual on geometry and geography data types. As far as I understand it, there are many more functions available for geometries, but you have to get involved with projections. The best choice depends on what you're doing...

SELECT polygonID, pointID
  FROM Points INNER JOIN Polygons 
  ON ST_covers(polygons.aPolygon,Points.thePoint  );

Upvotes: 4

Aleksandar Stojadinovic
Aleksandar Stojadinovic

Reputation: 5049

It's been some time now since I've done anything with PostGIS, but I'll give it a try.

SELECT polygonID, pointID FROM Points, Polygons WHERE ST_CONTAINS(Points.thePoint , polygonID.aPolygon);

Upvotes: 0

Jasen
Jasen

Reputation: 12442

postgresql has polygon @> point

select * from points join polygons on polygons.aPolygon @> points.thePoint;

Upvotes: 1

Related Questions