Creating 3D points in PyQGIS?

In QGIS v3.0 you can use directly QgsPoint:

zPoint = QgsPoint(-74, 4, 2600) # x, y, z
zPoint.z()  # Prints 2600.0

Whereas in QGIS >= 2.10 you need to use QgsPointV2:

zPoint = QgsPointV2( QgsWKBTypes.PointZ, -74, 4, 2600 ) # type, x, y, z
zPoint.z()  # Prints 2600.0

This is an example with a memory layer using QGIS 2.14 (based on the PyQGIS Cookbook):

from PyQt4.QtCore import QVariant

# create layer
vl = QgsVectorLayer( "Point", "Points with Z", "memory" )
pr = vl.dataProvider()

# add fields
pr.addAttributes( [QgsField("name", QVariant.String),
                    QgsField("age",  QVariant.Int),
                    QgsField("size", QVariant.Double)] )
vl.updateFields() 
QgsMapLayerRegistry.instance().addMapLayer( vl )

# add a feature
fet = QgsFeature()
fet.setGeometry( QgsGeometry( QgsPointV2( QgsWKBTypes.PointZ, -74, 4, 2600 ) ) )
fet.setAttributes( ["Johny", 2, 0.3] )
pr.addFeatures( [fet] )
vl.updateExtents()

# Read feature's geometry
f = iface.activeLayer().getFeatures().next()
g = f.geometry()
g.geometry().z()  # Prints 2600.0
g.geometry().asWkt() # Prints u'PointZ (-74 4 2600)'
g.exportToWkt()  # Prints u'PointZ (-74 4 2600)'

Tags:

3D

Point

Pyqgis