POSTGIS: find all the points within a polygon

巧了我就是萌 提交于 2019-12-08 01:39:02

问题


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.


回答1:


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  );



回答2:


postgresql has polygon @> point

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



回答3:


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);




回答4:


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.



来源:https://stackoverflow.com/questions/27830521/postgis-find-all-the-points-within-a-polygon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!