I have a list of features selected in the mapcanvas and for those selected features I am doing a buffer and printing the feature names that are inside the buffer. While printing, all values in the list have the same state and cities name. I don't know where I am wrong. I had also attached my code for reference.

layer = iface.activeLayer()
selection = layer.selectedFeatures()
for feature in selection:
 buff = feature.geometry().buffer(80467.22489462817, 2)
 iterFeat = layer.getFeatures()
for f in iterFeat:
 geom2 = f.geometry()
 valTest = QgsGeometry.within(geom2, buff)
 if valTest:
    idx = layer.fieldNameIndex('name')
    idx1 = layer.fieldNameIndex('state')
    lsNearCities = []
    nearCity = feature.attributes()[idx]
    state = f.attributes()[idx1]
    state_and_cities = str(state) + "," + nearCity
    print lsNearCities

I believe you want this line:

nearCity = feature.attributes()[idx]

to be:

nearCity = f.attributes()[idx]

Using the feature variable will always point to the last value in selection.

(This is untested advice, so I might not be understanding something fundamental here.)

  • Thank you Richard Morgan. Really great!That works.Its simple though. – User123 Mar 7 '15 at 18:32

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.