PyQGIS: How to Loop Over Features from Two Different Vector Layers?

المشرف العام

Administrator
طاقم الإدارة
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!"

أكثر...
 
أعلى