Thursday, 28 September 2017

qgis - How to find the polygon inside which a point lies?


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:



  1. Create a list of QgsPoint from your coordinates

  2. Iterate over all your layer features (polygons)

  3. Loop over the list of points (within the iteration)

  4. 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



  1. Create a list of QgsPoint from your coordinates

  2. Create a QgsSpatialIndex

  3. Iterate over all your layer features (polygons)

  4. Add the features to your index with insertFeature


  5. Iterate over all your points

  6. 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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...