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 LineString
s out of Point
geometries, or is this just not possible?
line.AddPoint()
. It looks to be failing because you're trying to useline.AddGeometry()
instead in the second exampleLineString
object. I want to, instead, pass thePoint
geometries themselves. Note how in the first example, there is a statement that saysmultiline.AddGeometry(line2)
. Here, I am adding aLineString
geometry to anotherMultiLineString
object. I want to know if it is possible to do something analogous, but addingPoint
geometries to aLineString
geometry. Sorry if I wasn't very clear in my original question.line.AddGeometry(pt1)
andline.AddPoint(pt1)
. Sadly, both failed.AddGeometry()
only seems to be meant for use on geoms of typewkbGeometryCollection
. But you could at least unpack them from the point objects themselves if you don't have access to the original coords, withline.AddPoint(*pt1.GetPoint())
or whatever