When I instantiate a new wkbPoint
geometry and give it only two coordinates, I expect it to be specifically 2D. However, a third coordinate automatically gets added as 0. See my code below:
from osgeo import ogr
coords = [12, 34]
pt = ogr.Geometry(ogr.wkbPoint)
pt.AddPoint(*coords)
print(pt.ExportToWkt())
#POINT (12 34 0)
Note how, at the end of the code, the pt
variable has 3 coordinates instead of just 2. Why is this happening, and, more importantly, how can I force the creation of a 2D Point
object?
Note
I was able to find the answer to my own question before asking it, but I still wanted to post it here as a resource for future users.
Best Answer
The reason why you're getting a 3D object is because you are using the
AddPoint
method instead of theAddPoint_2D
method. As seen in theOSGEO
/OGR
/GDAL
documentation, theAddPoint
method expects all three coordinates as arguments:x
,y
andz
. If you only pass it two arguments, it will assumez=0
.If, instead, you really want to work with 2D geometries, just use the
AddPoint_2D
method (and, in general, other methods that have the_2D
suffix).Here's an example that fixes your specific problem:
Note how the geometry now only has two dimensions.