3

Consider the following SQLAalchemy / GeoAlchemy2 ORM with a geometry field:

from geoalchemy2 import Geometry, WKTElement

class Item(Base):

    __tablename__ = 'item'

    id = Column(Integer, primary_key=True)
    ...
    geom = Column(Geometry(geometry_type='POINTZ', srid=4326))

When I update an item in the PostgreSQL shell:

UPDATE item SET geom = st_geomFromText('POINT(2 3 0)', 4326) WHERE id = 5;

Fetching the field:

items = session.query(Item).\
    filter(Item.id == 3)

for item in items:
    print item.geom

Gives:

01e9030000000000000000004000000000000008400000000000000000

This isn't a proper WKB - at least, it does not parse with Shapely's loads.

How do I get the lat/lon of the geom field?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562

3 Answers3

6

Fetching the lat, lon via ST_X and ST_Y might not be the most elegant approach, but it works:

from sqlalchemy import func

items = session.query(
            Item, 
            func.st_y(Item.geom), 
            func.st_x(Item.geom)
        ).filter(Item.id == 3)

for item in items:
    print(item.geom)

Gives:

(<Item 3>, 3.0, 2.0)
jfunez
  • 397
  • 6
  • 23
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 1
    How do I do it without access to the session? I'm trying to add lat & lng properties to my point model for easy access. – Nick Sweeting Feb 25 '16 at 02:14
5

geoalchemy2 to_shape function to convert a :class:geoalchemy2.types.SpatialElement to a Shapely geometry.

in Item class :

from geoalchemy2.shape import to_shape

point = to_shape(self.geo)

return {
    'latitude': point.y,
    'longitude': point.x
}
jfunez
  • 397
  • 6
  • 23
mosi_kha
  • 512
  • 6
  • 7
0

Point type syntax is

Point ( Lat, Long)  

So basic from mosi_kha's answer, return should be

from geoalchemy2.shape import to_shape

point = to_shape(self.geo)

return {
    'latitude': point.x,
    'longitude': point.y
}
Fanco
  • 54
  • 3