6

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

7
  • 1
    Well, since you're returning the centroid of the line, it's no surprise you only get point coordinates.
    – Erik
    Commented Sep 21, 2020 at 12:59
  • 1
    You use centroid's coordinates. Commented Sep 21, 2020 at 13:00
  • 1
    I am not sure if I understand what you try to achieve, but I think the '.asWkt()' function would be helpful: for f in lyr.getFeatures(): print(f.aswkt())
    – Sam
    Commented Sep 21, 2020 at 13:01
  • @Erik. What is the best way to extract coordinates(Lat,Long) from line layer?
    – Case Msee
    Commented Sep 21, 2020 at 13:15
  • 1
    @CaseMsee You mean to store it as an attribute? sure! I recently used this question to edit a feature's attributes. You can create a new string attribute and edit it with the value of "f.geometry().asWkt()"
    – Sam
    Commented Sep 21, 2020 at 13:24

1 Answer 1

10

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)
6
  • 1
    Great answer. The only thing is: the above code produces MULTILINESTRING geometry in the attribute table. Is it possible to convert MULTILINESTRING to LINESTRING as shown in first image of question?
    – Case Msee
    Commented Sep 21, 2020 at 13:32
  • 6
    Your layer probably contains multilinestrings. Use Convert geometry type tool in Processing Toolbox to convert to Linestring before. Commented Sep 21, 2020 at 13:37
  • 1
    Thank you. This is what I was thingking. Is it possible to plot MULTILINESTRING coordinates in the QGIS? Mapping XY coordinates are simple but I was wondering about MULTILINESTRING coordinates
    – Case Msee
    Commented Sep 21, 2020 at 13:38
  • 3
    You can ask another question about it. QuickWKT plugin may help. I don't understand what exactly you mean. Commented Sep 21, 2020 at 13:42
  • 2
    Only an advice: I wrote the same but instead "geometry" I wrote 'geometry' and it has worked! Commented Dec 15, 2022 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.