TransWikia.com

Getting Polyline (Linestring) coordinates from line layer in QGIS

Geographic Information Systems Asked on June 20, 2021

I have a road network (line layer). I am trying to get list of coordinates (Lat,Long) from road network in the form of geometry LINESTRING as shown below. However, I am only getting two coordinates as shown in second figure.

enter image description here

What I have tried:

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)

enter image description here

One Answer

First, add a field (name: geometry, type: string, length: 1000 keep it long). Then use the following script:

lyr = iface.activeLayer()

with edit(lyr):
    for f in lyr.getFeatures():
        f["geometry"] = f.geometry().asWkt()
        lyr.updateFeature(f)

Correct answer by Kadir Şahbaz on June 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP