Why does OSGEO/OGR add a third dimension to the 2D geometry

3ddimensionsogrosgeopython

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 the AddPoint_2D method. As seen in the OSGEO/OGR/GDAL documentation, the AddPoint method expects all three coordinates as arguments: x, y and z. If you only pass it two arguments, it will assume z=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:

from osgeo import ogr

coords = [12, 34]

pt = ogr.Geometry(ogr.wkbPoint)
pt.AddPoint_2D(*coords)
print(pt.ExportToWkt())
#POINT (12 34)

Note how the geometry now only has two dimensions.