4

I would like to save x,y,z values for polygon vertices as a geoJSON file using Python in QGIS. I've made several attempts, but all have issues. I've found that the QgsPoint object must be used as QgsPointXY does not support Z and M values. Below is a code snippet which includes various tries and their corresponding error messages/issue:

for idx in range(n):
   col = int(round((geom.vertexAt(idx).x() - extent.xMinimum()) / xres))
   row = int(round((extent.yMaximum() - geom.vertexAt(idx).y()) / yres))
  
   lat = round(self.ur_lat - (row * lat_res), 6)
   lon = round(self.ll_lon + (col * lon_res), 6)
   alt = computeAltFromLatLon     
   point=QgsPoint(lon, lat,alt)
   lat_lon_points.append(point)

# Error: type object 'QgsGeometry' has no attribute 'fromPolygonZ'
# lat_lon_poly = QgsGeometry.fromPolygonZ([lat_lon_points])
 
# Error: type object 'QgsGeometry' has no attribute 'fromPolygon'
#lat_lon_poly = QgsGeometry.fromPolygon([lat_lon_points])
 
# Error: index 0 has type 'QgsPoint' but 'QgsPointXY' is expected
#    QgsPointXY does not support Z and M values
#lat_lon_poly = QgsGeometry.fromPolygonXY([lat_lon_points])
 
# File is successfully written here, but only x,y is saved.
lat_lon_poly = QgsGeometry.fromPolyline([lat_lon_points[0], 
lat_lon_points[1],lat_lon_points[2], lat_lon_points[3]])
  
fet.setGeometry(lat_lon_poly)
 
# print("Write to GeoJSON: ")
writer.addFeature(fet)

Any suggestions for how I can write a geoJSON file with x,y,z values for each coordinate?

4

To create a PolygonZ use the following structure:

QgsGeometry( QgsPolygon( QgsLineString( lat_lon_points ) ) )

Example:

points = [QgsPoint(1,1,1), QgsPoint(1,2,2), QgsPoint(2,2,3)]

geometry = QgsGeometry( QgsPolygon( QgsLineString( points ) ) )

print(geometry)
# <QgsGeometry: PolygonZ ((1 1 1, 1 2 2, 2 2 3, 1 1 1))>) )

fet.setGeometry(geometry)

enter image description here

3
  • Thanks for the suggestion, but I'm getting an error when I try the code: QgsPolygon(): arguments did not match any overloaded call: overload 1: too many arguments, overload 2: argument 1 has unexpected type 'QgsLineString' – mjldbr Jan 19 at 21:58
  • What is QGIS version you use? – Kadir Şahbaz Jan 20 at 7:42
  • I am using version 3.12 - it looks like I need to upgrade. Thank you for your help! I'll accept this as the answer. – mjldbr Jan 20 at 13:39
0

Instead of trying to use the QGIS objects and built-in writer, I just created the file using the json package. For the coordinates I used an array of x,y,z values. I'm not able to copy/paste the code as the computer I was working on does not have internet access.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.