Geographic Information Systems Asked on July 6, 2021
I have a road network in form of lines. I retreived the Lat/Long using field calculter in QGIS.
The method I used was:
long: x(centroid($geometry)), for lat y(centroid($geometry))
However, i want to getting the Lat/Long using PyQGIS. The PyQGIS script should automatically add the Lat/Long points in the attribut table of active layer. I tried below script but it is not working.
from qgis.utils import iface
feat = QgsFeature()
mc = iface.mapCanvas()
layer = mc.layer(0)
provider = layer.dataProvider()
provider.select()
while(provider.nextFeature(feat)):
geometry = feat.geometry()
print "X Coord %d: " %geometry.asPoint().x()
print "Y Coord %d: " %geometry.asPoint().y()
lyr = iface.activeLayer()
fl = ['lat','lon'] #Add these fields before executing code
with edit(lyr):
for f in lyr.getFeatures():
p = f.geometry().centroid().asPoint()
_=f.setAttribute(f.fields().indexFromName(fl[0]), p.y())
_=f.setAttribute(f.fields().indexFromName(fl[1]), p.x())
_=lyr.updateFeature(f)
Correct answer by BERA on July 6, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP