1

I am trying (and failing) to generate M-value geometries (e.g. POINT M, POINT ZM, LINESTRING M, ...) with Python's osgeo/ogr library.

Here is what I've tried to far:

import ogr 

# Use OGR specific exceptions
ogr.UseExceptions()

# Creating a list of coordinates
coords = [0, 0, 0]

# Creating a POINT M geometry
point = ogr.Geometry(ogr.wkbPointM)

# Adding the actual point data
point.AddPoint(*coords)

# Extracting the WKT of the newly-created geometry
print(point.ExportToIsoWkt())

> POINT Z (0 0 0)

The code above outputs a POINT Z geometry, not a POINT M geometry. The third value is being interpreted as a regular coordinate, not an M-value.

How can I avoid this?

A cumbersome workaround

I know one dirty trick that works: to use WKT instead. Here's the code:

# Creating a list of coordinates
coords = [0, 0, 0]

# Making a WKT string
pt_wkt = f'POINT M({" ".join([str(coord) for coord in coords])})'


# Converting the WKT string to a geometry
pt_ogr = ogr.CreateGeometryFromWkt(pt_wkt)

# Extracting the WKT back out from the geometry
print(pt_ogr.ExportToIsoWkt())
> 'POINT M (0 0 0)'

The snippet above works: it generates a POINT M geometry, as expected. However, converting a list of coordinates into a WKT can be quite cumbersome, depending on the type of geometry. Also, the creation of this ogr geometry is just going to be a small part of a larger process, so I want to avoid the conversion of a list of coordinates to a WKT string. If I can figure out the correct way to use the wkbPointM geometry (and all other M-value geometries), I might be able to speed things up significantly.

So, I am back to my main question: what is the correct way to create M-value-enabled geometries using Python's osgeo/ogr library from a list of coordinates without converting them into a WKT first?

1 Answer 1

4

Try AddPointM() instead of AddPoint():

AddPointM(Geometry self, double x, double y, double m)

https://gdal.org/python/osgeo.ogr.Geometry-class.html#AddPointM

1
  • It worked! Thank you so much for the advice!!! So simple, hahahahaha...
    – Felipe D.
    Oct 14, 2021 at 0:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.