Thursday, 14 January 2016

geometry - Adding Z value from a Point field to a LineString using pyqgis


I Have two layer in Shapefile format:



  • a line layer made from a set of point which is a polyline 3D with z value to 0.

  • a point layer which contains elevation in a field (field_4)


Each point is located on a vertex of the line. See below:enter image description here


What I want to do is to had the Z value containing in the field_4 of the point layer to the coresponding vertex.


I found the setZAt method from QgsLineStringV2 which seems to exactly fit my need. So I wrote this code snippet :



line_layer  = QgsMapLayerRegistry.instance().mapLayersByName('line_truck')[0]
point = QgsMapLayerRegistry.instance().mapLayersByName('RT03')[0]
line_layer.startEditing()

for feat in line_layer.getFeatures():
for i, elem in enumerate(point.getFeatures()):
#get the point lying on the vertex
if str(feat.geometry().vertexAt(i).x())+str(feat.geometry().vertexAt(i).y()) == str(elem.geometry().asPoint().x())+str(elem.geometry().asPoint().y()):
print i , elem['field_4']
#update z value but nothing happen...

#feat.geometry().geometry is a QgsLineStringV2
feat.geometry().geometry().setZAt(i, elem['field_4'])

When I run it, the print statement show me the right values but the z value isn't updated in my feature...


Do I miss some steps or make a mistake in my logic??



Answer



I figured out the solution by my own


Actually, the geometry generate by the for loop was right


feat.geometry().geometry().setZAt(i, elem['field_4'])


but the feature geometry also need to be updated with this new geometry



so adding


line_layer.changeGeometry(feat.id(), feat.geometry())

at the end of the fisrt loop solve the issue!


The whole code become:


line_layer  = QgsMapLayerRegistry.instance().mapLayersByName('line_truck')[0]
point = QgsMapLayerRegistry.instance().mapLayersByName('RT03')[0]
line_layer.startEditing()

for feat in line_layer.getFeatures():

for i, elem in enumerate(point.getFeatures()):
#get the point lying on the vertex
if str(feat.geometry().vertexAt(i).x())+str(feat.geometry().vertexAt(i).y()) == str(elem.geometry().asPoint().x())+str(elem.geometry().asPoint().y()):
#update z value but nothing happen...
#feat.geometry().geometry is a QgsLineStringV2
feat.geometry().geometry().setZAt(i, elem['field_4'])
print feat.geometry().exportToWkt() #show the right geom with z values
line_layer.changeGeometry(feat.id(), feat.geometry())

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...