How to get lng lat value from query results of geoalchemy2

4.9k Views Asked by At

For exammple,

class Lake(Base):
     __tablename__ = 'lake'
     id = Column(Integer, primary_key=True)
     name = Column(String)
     geom = Column(Geometry('POLYGON'))
     point = Column(Geometry('Point'))


lake = Lake(name='Orta', geom='POLYGON((3 0,6 0,6 3,3 3,3 0))', point="POINT(2 9)")
query = session.query(Lake).filter(Lake.geom.ST_Contains('POINT(4 1)'))
for lake in query:
     print lake.point

it returned <WKBElement at 0x2720ed0; '010100000000000000000000400000000000002240'>

I also tried to do lake.point.ST_X() but it didn't give the expected latitude neither

What is the correct way to transform the value from WKBElement to readable and useful format, say (lng, lat)?

Thanks

5

There are 5 best solutions below

0
On

I did it the following way


class BusDepotGeoFence(models.Base):
    __tablename__ = "bus_geofence_data"

    id = Column(Integer, primary_key=True)
    area = Column(Geometry("POLYGON"))

The querying part as follows

    query = select(ST_AsGeoJSON(BusDepotGeoFence.area).label("area"))
    results = await db.execute(query)
    results = results.fetchall()
    results = [i[0] for i in results]
    results = [json.loads(result) for result in results]

0
On

Extending John's answer, you can use ST_AsText() while querying like this -

import sqlalchemy as db
from geoalchemy2 import Geometry
from geoalchemy2.functions import ST_AsText

# connection, table, and stuff here...

query = db.select(
    [
        mytable.columns.id,
        mytable.columns.name,
        ST_AsText(mytable.columns.geolocation),
    ]
)

Find more details on using functions here - https://geoalchemy-2.readthedocs.io/en/0.2.6/spatial_functions.html#module-geoalchemy2.functions

4
On

http://geoalchemy-2.readthedocs.org/en/0.2.4/spatial_functions.html#geoalchemy2.functions.ST_AsText is what you are looking for. This will return 'POINT (lng, lat)'. ST_X ought to work, though, so you may have another issue if it isn't returning the correct value.

0
On

Using shapely.

from shapely import wkb
for lake in query:
    point = wkb.loads(lake.point.data.tobytes())

    latitude = point.y
    longitude = point.x

Source https://stackoverflow.com/a/30203761/5806017

0
On

You can parse WKB (well-known binary) points, and even other geometry shapes, using shapely.

from shapely import wkb
for lake in query:
    point = wkb.loads(bytes(lake.point.data))
    print point.x, point.y