Creating LineString geometry from Point geometries with Python’s OSGEO/OGR library

linestringogrosgeopointpython

Is it possible to create a LineString object with Python's osgeo/ogr library starting from multiple Point objects?

For example, I know from the Python GDAL/OGR Cookbook that I can create a MultiLineString by adding multiple LineString objects:

from osgeo import ogr

multiline = ogr.Geometry(ogr.wkbMultiLineString)

line1 = ogr.Geometry(ogr.wkbLineString)
line1.AddPoint_2D(1214242.4174581182, 617041.9717021306)
line1.AddPoint_2D(1234593.142744733, 629529.9167643716)
multiline.AddGeometry(line1)

line2 = ogr.Geometry(ogr.wkbLineString)
line2.AddPoint_2D(1184641.3624957693, 626754.8178616514)
line2.AddPoint_2D(1219792.6152635587, 606866.6090588232)
multiline.AddGeometry(line2)

print(multiline.ExportToWkt())

However, when I use this idea to create a LineString from multiple Point geometries, it doesn't work:

from osgeo import ogr 

coords_p1 = [1214242.4174581182, 617041.9717021306]
coords_p2 = [1234593.1427447330, 629529.9167643716]

pt1 = ogr.Geometry(ogr.wkbPoint)
pt1.AddPoint_2D(*coords_p1)

pt2 = ogr.Geometry(ogr.wkbPoint)
pt2.AddPoint_2D(*coords_p2)

line = ogr.Geometry(ogr.wkbLineString)
line.AddGeometry(pt1)
line.AddGeometry(pt2)

When I try to run the snippet above, it gives me the following error:

Traceback (most recent call last):

File "C:\Users\diasf\AppData\Local\Temp/ipykernel_43960/3403084045.py", line 11, in

line.AddGeometry(pt1)

File "C:\ProgramData\Anaconda3\envs\myenv\lib\site-packages\osgeo\ogr.py", line 6245, in AddGeometry

return _ogr.Geometry_AddGeometry(self, *args)

RuntimeError: OGR Error: Unsupported geometry type

I know the snippet above would work if I used line.AddPoint(*coords_p1) instead of line.AddGeometry(pt1) (i.e., it works if I pass each point's coordinates to the LineString object instead of trying to add the actual Point geometries).

But is there a way to build LineStrings out of Point geometries, or is this just not possible?

Best Answer

As pointed out by @mikewatt, it seems like I cannot add a point geometry directly. The best I can do is use the GetPoint or GetPoint_2D methods and pass the Point geometry's coordinates to the LineString geometry, as shown below:

from osgeo import ogr

coords_p1 = [1214242.4174581182, 617041.9717021306]
coords_p2 = [1234593.1427447330, 629529.9167643716]

pt1 = ogr.Geometry(ogr.wkbPoint)
pt1.AddPoint_2D(*coords_p1)
print(pt1.ExportToWkt())
#POINT (1214242.41745812 617041.971702131)

pt2 = ogr.Geometry(ogr.wkbPoint)
pt2.AddPoint_2D(*coords_p2)
print(pt2.ExportToWkt())
#POINT (1234593.14274473 629529.916764372)

line = ogr.Geometry(ogr.wkbLineString)

line.AddPoint_2D(*pt1.GetPoint_2D())
line.AddPoint_2D(*pt2.GetPoint_2D())

print(line.ExportToIsoWkt())
# LINESTRING (1214242.41745812 617041.971702131,1234593.14274473 629529.916764372)