3

I'm fairly new to using PyQgis, so sorry if this question is basic. I'm working with two vector layers:

(layer 1) A series of polygons, each with an ID field specifying what geographic district the polygon is in

(layer 2) A series of points, also with the same ID field as above

I am trying to determine what points from layer 2 lie within a polygon with a matching ID field from layer 1.

As a start, I decided I would loop over all of the polygons in layer 1, and for each polygon, loop over all of the points in layer 2 to see if the ID fields of each polygon/point matched. The ID field in layer 1 is attribute number 10. The corresponding ID field in layer 2 is attribute number 1. My problem is that, in the following code, only the first feature in layer 1 gets looped over. So, while there are about 200 or so polygons in layer 1, each with a unique ID, the code only loops over a single ID corresponding to a single polygon.

Here's what I have:

layer1 = QgsVectorLayer('shapefile1_location', "polygon_layer")
if not layer1:
  print "Layer 1 failed to load!"

layer2 = QgsVectorLayer('shapefile2_location', "points_layer")
if not layer2:
  print "Layer 2 failed to load!"


layer1 = iface.addVectorLayer('shapefile1_location', "polygon_layer", "ogr")
layer2 = iface.addVectorLayer('shapefile2_location', "points_layer", "ogr")


iter1 = layer1.getFeatures()
iter2 = layer2.getFeatures()
for polygon in iter1:
    for point in iter2:
        if polygon[10]==point[1]:
            print polygon[10], "Success!"
1
  • Detlev is right. Also, to test if the point lies within the polygon you could do it like this: polygon.geometry().contains(point.geometry()). Oct 26, 2015 at 12:15

1 Answer 1

2

QgsVectorLayer.getFeatures() is an iterator that yields the next value each time it is called. Therefore you must call it repeatedly to iterate through all possible values.

Change your code as following:

for polygon in layer1.getFeatures():
    for point in layer2.getFeatures():
        if polygon[10]==point[1]:
            print polygon[10], "Success!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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