Monday, 18 July 2016

pyqgis - Changing the coordinate value of a Pointz object with python


How can I change the X,Y or Z value of a Pointz feature with python in QGIS? I am trying to change the Z values of Pointz with a python plugin. I am first trying to pass the selected feature to a variable in the program. I can get to the geometry in the program and on the console.


selection = layer.selectedFeatures()[0]
geom = selection.geometry()
print(geom)
767.54999999999995453)>

Then I get stuck trying to get the Z coordinates out. I have tried the geom.z() and geom.id() and I get errors. geom.asPoint()[1] does give me the X and Y values but not the Z. Is there a way to get and change the "Z"



767.54999999999995453)>
geom.x()
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
AttributeError: 'QgsGeometry' object has no attribute 'x'

UPDATE


This is similar to what I ended up with. The lines with wkt in them generate the geometry from "well known text". This did work but I took it out for the better .setX() method. You would have to change the feature.setGeometry(geom) to feature.setGeometry(new_pnt) to use that method.



layer = iface.activeLayer()
print(layer)
all_features = layer.getFeatures()
layer.startEditing()
for feature in all_features:
print(feature['NUMBER'])
if feature['NUMBER'] == '1003':
print('found it ********\n ')
feature['SUMPDIST'] = '18.55'
geom = feature.geometry()

print(geom)
new_feat = QgsFeature()
point1 = QgsPoint(26132109.5, 644411.8, 940.600)

#new_pnt = QgsGeometry.fromWkt("POINTZ(26132109.5 644411.8 940.48)")
wkt = "POINTZ(" + str(point1.x()) + " " + str(point1.y()) + " " + str(point1.z()) +")"
new_pnt = QgsGeometry.fromWkt(wkt) #This well known text works also But I like the .setX, .setY, .setZ method much better.
geom.get().setX(point1.x())
geom.get().setY(point1.y())
geom.get().setZ(point1.z())

feature.setGeometry(geom)

layer.updateFeature(feature)
print('feature '+feature['SUMPDIST'])
print(str(point1.z()))
print(str(feature.geometry().get().z()))

break
layer.commitChanges()
print(str(feature.geometry().get().z()))


Answer



You need to access the underlying QgsPoint object. Think of QgsGeometry as a "container" which holds a point, line, polygon, etc. To do this you call ".get()" on the QgsGeometry.


I.e.


geom.get().x()
geom.get().z()
geom.get().setZ(5)

Etc


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