More

Using ST_LINE_INTERPOLATE_POINT in OGR and Python

Using ST_LINE_INTERPOLATE_POINT in OGR and Python


I'm interested in finding the midpoint on a linestring using OGR and Python. This can be a line with more segments. Could I use the ST_LINE_INTERPOLATE_POINT in Python using the ExecuteSQL() method?

If so, could someone perhaps help me formulate the correct SQL query? Or is there an alternative option? I considered using Centroid but the centroid can also lie outside of the geometry.

---- UPDATE ----
I have QGIS installed on Windows and use the OSGeo4W shell. I made the following Python code but unfortunately it doesn't work, geom is seen as a NoneType.

from osgeo import ogr outdriver=ogr.GetDriverByName('SQLITE') source=outdriver.CreateDataSource('temp') tmp=outdriver.Open('temp') layer = tmp.ExecuteSQL("""SELECT ST_AsText(ST_Line_Interpolate_Point(ST_GeomFromText('LINESTRING ( 90 379, 99 278, 189 224, 297 193, 403 189, 459 202 )'),0.5))""") geom = layer.GetNextFeature().GetGeometryRef() print geom.ExportToWkt()

As described in https://www.gaia-gis.it/gaia-sins/spatialite-sql-latest.html the function is used as

ST_Line_Interpolate_Point( line Curve , fraction Double precision ) : Point

An example that can be tested with SQL command line for example with spatialite-gui. Fraction=0.5 finds the midpoint.

SELECT ST_AsText( ST_Line_Interpolate_Point (ST_GeomFromText('LINESTRING ( 90 379, 99 278, 189 224, 297 193, 403 189, 459 202 )'),0.5)) POINT(222.434071 214.403183)

You can use that query as a template for your ExecuteSQL(). Remember that you must use the SQLite SQL dialect and GDAL must be compiled with such Spatilite version that has the ST_Line_Interpolate_Point function.


The PyQGIS geometry object (QgsGeometry) has an interpolate function. The OGR geometry object I am using does not. So I will use QgsGeometry instead.

See: https://woostuff.wordpress.com/2012/08/05/generating-chainage-distance-nodes-in-qgis/