3

I have one polygon and onde shp of points (some within and others without the polygon). I have tried the following code:

layers = QgsProject.instance().mapLayers()

for feature in layers['poly_teste_1'].getFeatures():
    geom_poly=feature.geometry()

for feature2 in layers['points_test2_2'].getFeatures():
    geom_point=feature2.geometry()
i=0
for points in layers['pointo_test2_2'].getFeatures():
    if geom_poly.contains(geom_point):
        i=i+1


print(i)

The problem is that the code a printing the total number of points, and not only the ones that are within the polygon.

3

(in the second loop) : you assign geom_point the geometry of the last point found in your point layer (last of the loop, depending of your table's objects order ...)

(In the third loop) : you 'play' with this geom_point which is "a" point (obviously in your polygon) but you're not iterating over all the points of your point layer.

That's not a gis issue but a programming issue ...

2
  • Ok! Now I see that. Thanks.. the if inside the second loop solved the problem – caio villaca Jun 19 '19 at 17:30
  • At least half of questions at SE GIS are then programming issues since people do not know how to write code to get desired result or make mistakes when writing the code. – TomazicM Jun 19 '19 at 17:33
2

A simple way can be use the processing algorithms "Select by location", where PREDICATE: [6] means "are within"

processing.run("native:selectbylocation", {'INPUT':point_layer,'PREDICATE':[6],'INTERSECT':polygon_layer,'METHOD':0})
point_layer.selectedFeatureCount()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.