I have a layer with polygonal features. Each feature has attributes and values. I also have a list of co-ordinates and I would like to know which feature (or polygon) the co-ordinates lie in.
Could someone please guide me on how to go about this? Is there a function in the API that can help me achieve my goal or should I use some computational geometry algorithm to do it myself? I know how to do the latter but it would save me some time if there was a built in function already.
Thanks.
Answer
Few features
What you probably want to do is:
- Create a list of QgsPoint from your coordinates
- Iterate over all your layer features (polygons)
- Loop over the list of points (within the iteration)
- Call feature.geometry().contains( point ) to check if you've got a match
Of course you can now improve performance if you e.g. know, that a point can only be contained by one polygon, you can remove a point from the list, once the appropriate polygon has been found.
Lots of features (Using SpatialIndex)
As pointed out in the comments, a spatial index can be used to speed up the process significantly.
The steps here would be
- Create a list of QgsPoint from your coordinates
- Create a QgsSpatialIndex
- Iterate over all your layer features (polygons)
- Add the features to your index with insertFeature
- Iterate over all your points
- Call index.intersects( QgsRectangle( point, point ) ) to check if you've got a match
There is also a code example by NathanW
No comments:
Post a Comment