Is there any simple integration for calculating count of points in polygon using QGIS-Python integration?
In other words, are there any pre-defined functions for points in polygon of QGIS using python, so that we can use them in our python script?
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.Sign up to join this community
Great methods already posted! There are also tools from the Processing Toolbox which you could call from your script (this is assuming you are running scripts inside QGIS):
Taking the first tool, you could call it using:
import processing Result = "path\to\saved_output.shp" processing.runalg("qgis:countpointsinpolygon", "path\to\polygon_layer.shp", "path\to\point_layer.shp", 'NUMPOINTS', Result)
NUMPOINTS is the name of the field which stores the number of points.
I'm using QGIS 2.8.2-Wien, Processing plugin v2.9.3. Hope this helps!
I rewrote my answer from a parallel question counting points in current atlas feature: How to count points within the current Print composer atlas feature in QGIS 2.8?
Build a new function in the expression editor:
from qgis.core import * from qgis.gui import * from qgis.utils import iface @qgsfunction(args="auto", group='Custom') def countPointsInPolygon(pointLayerName, geom, feature, parent): # If point geom is empty, return 0 if (geom is None): return 0 # Get point layer reference from layername pointLayer = QgsMapLayerRegistry.instance().mapLayersByName(pointLayerName) # Raise if layer not found if pointLayer is None: raise Exception("Layer not found: " + pointLayerName) # Count point within current polygon feature countPoint = 0 for pointFeature in pointLayer.getFeatures(): pointGeom = pointFeature.geometry() if (pointGeom is None): continue if pointGeom.within(geom): countPoint += 1 return countPoint
Use it as a expression on the polygon layer where 'mypoints' is the name of the point layer:
countPointsInPolygon( 'mypoints', $geometry )
If you don't want it implemented as an expression, you can call the function from your own script looping the features of the polygon layer calling countPointsInPolygon for each feature.
I have never worked with QGIS's python API, so my answer is a wild guess. But it looks like QGIS is using GEOS geometry objects similar to django. So this could work in QGIS too:
I assume your polygon is a qgsfeature :
I didn't test it but I guess it would work :
polygon.geometry() gives a qgsgeometry class.
qgsgeometry.asPolygon() gives a list of the point of your polygon.
Edit : You want the points inside the polygon? You have points in an other layer and wonder which ones intersect your polygon?