4

I have a geoalchemy2.elements.WKBElement that comes from a query on a Postgres/PostGIS view. I want to convert this to WKT, or otherwise encode it so that it is (Geo)JSON serialisable. How can I accomplish this?

Assuming similarity to shapely, I thought that geoalchemy2.elements.WKBElement would have a wkt property or class method, but it does not. The __str__ method returns the binascii.hexlify representation of the WKB. In the source for the geoalchemy2.elements there appears to be little else to use.

I'm about to build GDAL with python bindings to attempt to read the WKB and then output as WKT, but this feels like more work than I expected.

9

GeoAlchemy supports the PostGIS functions ST_AsText and ST_AsGeoJSON. You can use these in your query to return a WKT/GeoJSON string from the database instead of the WKBElement itself.

from geoalchemy2 import functions

# ...

wkt_qry = session.query(functions.ST_AsText(YourTable.geom))
geojson_qry = session.query(functions.ST_AsGeoJSON(YourTable.geom))

# ...

In fact, since the return type from these functions is just a string, you can also use the SQLAlchemy func object.

Update

If you need to store the WKBElement and get the WKT representation or other attributes at a later time you can use GeoAlchemy's shape module to convert the WKBElement to a Shapely geometry.

from geoalchemy2.shape import to_shape 

# ...   

# Return a WKBElement instance of your first geometry
wkb_elem = session.query(YourTable.geom).filter(YourTable.id==1).scalar()

# Convert to Shapely geometry
shply_geom = to_shape(wkb_elem)

# Print WKT representation
print shply_geom.to_wkt()
  • Easier than I thought! Thanks. To combine this with a SELECT * construct, I did session.query(Table, functions.ST_AsGeoJSON(Table.geom).label("geojson_geom")). – Richard Law Mar 23 '17 at 22:04
  • Just to be clear; using the session object like this means that the work is being done in the database server with a call to PostGIS ST_AsText. It's not happening in the Python code. Is there any way to do anything with the WKB blogs you get from GeoAlchemy2 without going to the database? – Nelson Oct 21 '17 at 19:02
  • 1
    @Nelson Yes, this utilises PostGIS functions in the database. I've updated my original answer to include an alternative approach for cases where you do want to get the WKBElement from the database and interrogate it later. – Ali Oct 23 '17 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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