I have a plugin which finds buffer for list of cities, provided the distance. The state and city names are taken from the attribute table and gets filtered accordingly. What I want is My plugin should identify the layer name or order of the layer in canvas,irrespective of other layers present in the canvas and access the corresponding attributes from that layer. Below is my code please say me where should I make changes and what would be the change? Thanks in advance.
def findTheCityNames(self):
self.dlg.Citycombo.clear()
ct = self.dlg.Statecombo.currentText()
st = "state='"+ct+"'"
exp = QgsExpression(st)
fidAndVal = {}
#QMessageBox.information(self.dlg, "info", st)
layer = self.iface.activeLayer()
iterFeat = layer.getFeatures()
for f in iterFeat:
val = exp.evaluate(f)
if bool(val):
attrs = f.attributes()
idx = layer.fieldNameIndex('name')
cityName = f.attributes()[idx]
fidInt = f.id()
fidAndVal[fidInt] = cityName
for x in fidAndVal.keys():
self.dlg.Citycombo.addItem(fidAndVal[x])
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