如何从geoalchemy2的查询结果中获取经纬度值

18 投票
5 回答
4979 浏览
提问于 2025-04-18 08:56

例如,

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

它返回了 <WKBElement at 0x2720ed0; '010100000000000000000000400000000000002240'>

我还尝试使用 lake.point.ST_X(),但没有得到预期的经度

那么,从WKBElement转换成可读且有用的格式,比如(经度,纬度),正确的方法是什么呢?

谢谢

5 个回答

0

我这样做的:


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

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

查询的部分如下:

    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

使用shapely库。

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

    latitude = point.y
    longitude = point.x

来源 https://stackoverflow.com/a/30203761/5806017

0

在约翰的回答基础上,你可以在查询时使用 ST_AsText(),方法如下 -

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),
    ]
)

想了解更多关于使用这些函数的细节,可以查看这里 - https://geoalchemy-2.readthedocs.io/en/0.2.6/spatial_functions.html#module-geoalchemy-2.functions

5

你可以看看这个链接:http://geoalchemy-2.readthedocs.org/en/0.2.4/spatial_functions.html#geoalchemy2.functions.ST_AsText。这个函数会返回类似'POINT (lng, lat)'这样的结果。ST_X这个函数应该也能正常工作,如果它没有返回正确的值,那可能是你遇到了其他问题。

14

你可以使用 shapely 来解析 WKB(著名的二进制格式)的点,甚至其他几何形状。

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

撰写回答