I can get the values of 3D QgsPoints with mypoint.get().z() When I iterate through a layer to get a specific polyline and then iterate through the polyline to get the start and end points- start_point = QgsPoint(geom[0]) I get a QgsPointXY and no Z values. They are there until the iteration geom[0] and then poof gone.
Is there a way to include the z values with something other than QgsPoint(geom[-1])?
My related question is Changing the coordinate value of a Pointz object with python – which is actually how I got the points to create the polyLine
I am taking this route next
Adding Z value from a Point field to a LineString using pyqgis
Below is the code I ran in the Python Console. The output is also below.
layer = iface.activeLayer()
print(layer)
all_features = layer.getFeatures()
layer.startEditing()
for pipe in all_features:
if pipe['name'] == '1212_1211':
print('found it ********\n ')
pipe_id = pipe.id()
geom = pipe.geometry()
print(geom)
new_feat = QgsFeature()
geom = pipe.geometry().asPolyline()
start_point = QgsPoint(geom[0])
end_point = QgsPoint(geom[-1])
print (start_point)
print (start_point.x())
OUTPUT
<qgis._core.QgsVectorLayer object at 0x000001767C312EE8>
found it ********
<QgsGeometry: LineStringZ (26138560.91000000014901161 643574.7099999999627471 778.20000000000004547, 26138558.94000000134110451 643563.81000000005587935 0)>
<QgsPoint: Point (26138560.91000000014901161 643574.7099999999627471)>
26138560.91
UPDATE
I found a great chunk of code from this site that made this work for QGIS 3 – geom.constGet() is the key below. How to access shapefile m-values with pyqgis?
layer = iface.activeLayer()
print(layer)
all_features = layer.getFeatures()
layer.startEditing()
for pipe in all_features:
if pipe['name'] == '1212_1211':
print('found it ********\n ')
pipe_id = pipe.id()
geom = pipe.geometry()
line = geom.constGet() #line returns a QgsLineString object
z = line.zAt(0) # z value of first vertex
print(str(z))
Best Answer
It's a bit silly but as I look in the
QgsPoint
constructor like here: QGIS Python API: QgsPointI think you need to provide the 3 coordinates of the point in order to create a 3D point, if you only send a geom and if the wkbtype is unknown, he will cast it as a 2D point. So maybe try to explicitly give the 3 coordinates of the point before calling
QgsPoint
, something like :and then you do your stuff on
mypoint.get().z()
. There is also a method calledaddZvalue()
.