lundi 23 février 2015

How to select the buffer region in map canvas in my plugin using python


I am developing a plugin which finds buffer by getting state name, city name and distance given by the user. The plugin works fine and writes the cities that matches the distance in a CSV file. What i want is the buffer region should get selected in the map canvas. How it can be done. I had attached my code below.



def calcDistance(self):
lsNearCities = []

filePath = self.dlg.fileNameEdit.text()

if len(str(filePath)) ==0:
QMessageBox.warning(self.dlg, "File Name","Give it a file name and try again")
return

if self.dlg.DistancelineEdit.text():
dist = float(self.dlg.DistancelineEdit.text())/(0.000621371)
else:
dist = 0

centerCity = self.dlg.Citycombo.currentText()

if dist and centerCity:
#QMessageBox.information(self.dlg, "info", "both True")
st = '"name" = \'' + centerCity + '\''
exp = QgsExpression(st)
else:
QMessageBox.warning(self.dlg, "Enter the distance","Enter the distance and try again.")
return #terminate the function

layer = self.iface.activeLayer()
it = layer.getFeatures(QgsFeatureRequest(exp))
feature = it.next()
mbuf = feature.geometry().buffer(dist, 2)

iterFeat = layer.getFeatures()

for f in iterFeat:
geom2 = f.geometry()
valTest = QgsGeometry.within(geom2, mbuf)

if valTest:
idx = layer.fieldNameIndex('name') #name of the attribute column with the cities in it
idx1 = layer.fieldNameIndex('state')
nearCity = f.attributes()[idx]
state = f.attributes()[idx1]
state_and_cities = nearCity +","+ str(state)
lsNearCities.append(state_and_cities)
#call the function to write them into a file
self.writeToFile(lsNearCities, filePath)




Aucun commentaire:

Enregistrer un commentaire