Wednesday 21 November 2018

qgis - How to add vertex to an existing polyline programatically?


I have a Polyline and would like to add new vertex to before start point or end point or at any part of the polyline using python in qgis.


How can i do that?




Answer



First case: insert new polyline


You have to define the Polyline like so:


pLine = [QgsPoint(1,1), QgsPoint(2,1), QgsPoint(2,2)]

it is a list-of-QgsPoint. After you can put more QgsPoint into the list by append to insert the element at the end of the list:


pLine.append(QgsPoint(3,2))

or inserting some vertex point at a specific location of the list:


## insert value at index 1

pLine.insert(1, QgsPoint(1, 0.5))

in this case the result will be:


pLine = [QgsPoint(1,1), QgsPoint(1, 0.5), QgsPoint(2,1), QgsPoint(2,2), QgsPoint(3,2)]

To add the new feature to the layer:


## create and add to map canvas a memory layer
lineLayer = iface.addVectorLayer("LineString", "Line Layer", "memory")

## create a feature

ft = QgsFeature()
## get geometry from the list-of-QgsPoint
polyline = QgsGeometry.fromPolyline(pLine)
## set geometry to the feature
ft.setGeometry(polyline)

pr = lineLayer.dataProvider()
pr.addFeatures([ft])

Second case: change an existing polyline



To change an existing geometry e.g adding a new vertex to line:


## add element to the list-of-Qgspoint at index 2
pLine.insert(2, QgsPoint(2, 0.5))
## define geometry with the new vertex
polyline = QgsGeometry.fromPolyline(pLine)
## change the geometry
pr.changeGeometryValues({ft.id():polyline})

in order to display the new vertex you have to refresh the map canvas:


iface.mapCanvas().refresh()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...