0

I have some features selected by using "Select Features by Freehand" tool in QGIS and try to find the buffer for those selected features alone and write the city and state names within in the buffer to a csv file. My code and image is attached for a clear understanding. it is writing an csv file in the given location but nothing is found inside the csv.

enter image description here

And my code is

import csv
selection = layer.selectedFeatures()
layer = qgis.utils.iface.activeLayer()
columns=['name', 'state' ]
for feature in selection:
  mbuf = feature.geometry().buffer(50, 2)
  iterFeat = layer.getFeatures()
  for f in iterFeat:
    geom2 = f.geometry()
    valTest = QgsGeometry.within(geom2, mbuf)
    lsNearCities = []
    if valTest:
        idx = selection.fieldNameIndex('name')
        idx1 = selection.fieldNameIndex('state')
        nearCity = f.attributes()[idx]
        state = f.attributes()[idx1]
        state_and_cities = str(state) + "," + nearCity
        lsNearCities.append(state_and_cities)
        print lsNearCities
  • where is "feature" initialized? – vinayan Mar 1 '15 at 11:09
  • Sorry that was a mistake before and edited now. – User123 Mar 1 '15 at 11:13
1

the Line,

feature = layer.selectedFeatures() 

returns a list of QgsFeature. You will need to loop over it to process individual selections, like below.

layer = qgis.utils.iface.activeLayer()
for feature in layer.selectedFeatures():
    mbuf = feature.geometry().buffer(50, 2)
    iterFeat = layer.getFeatures()
    for f in iterFeat:
      geom2 = f.geometry()
  • Thank you for the response. If i have n features selected in the map? how should i edit the code accordingly. Sorry for the simple question am new to python and QGIS – User123 Mar 1 '15 at 11:53
  • @AhamedFarook - updated answer. – vinayan Mar 1 '15 at 11:57
  • I tried the above code in the edited post. It is showing "List Object has no attribute FieldNameIndex. – User123 Mar 1 '15 at 12:52
  • @AhamedFarook - selection.fieldNameIndex('name') should be feature.fieldNameIndex('name') – vinayan Mar 1 '15 at 12:55
  • I replaced as you suggested, but am getting output as ['1.44403824649,1.44403824649'] ['0.591242026714,0.591242026714'] ['0.174240282156,0.174240282156'] ['0.0893665232556,0.0893665232556'] instead of state and city names of the of the buffered features. – User123 Mar 1 '15 at 13:37

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.