Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeoAlchemy2: Get the lat, lon of a point

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?

like image 317
Adam Matan Avatar asked Nov 29 '25 05:11

Adam Matan


2 Answers

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
}
like image 136
mosi_kha Avatar answered Dec 02 '25 03:12

mosi_kha


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)
like image 44
Adam Matan Avatar answered Dec 02 '25 05:12

Adam Matan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!