GeoAlchemy2: 获取点的纬度、经度

3
考虑以下带有几何字段的SQLAlchemy / GeoAlchemy2 ORM示例:
from geoalchemy2 import Geometry, WKTElement

class Item(Base):

    __tablename__ = 'item'

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

当我在PostgreSQL shell中更新一个项目时:
UPDATE item SET geom = st_geomFromText('POINT(2 3 0)', 4326) WHERE id = 5;

获取字段:

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

for item in items:
    print item.geom

提供:

01e9030000000000000000004000000000000008400000000000000000

这不是一个合适的WKB格式——至少,它不能够用Shapely的loads函数解析。

我该如何获取geom字段的lat/lon

3个回答

6

通过使用ST_XST_Y来获取latlon可能不是最优雅的方法,但它可以正常工作:

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)

提供:

(<Item 3>, 3.0, 2.0)

1
我没有访问会话,该怎么做呢?我正在尝试为我的点模型添加lat和lng属性以便轻松访问。 - Nick Sweeting

5

geoalchemy2中的to_shape函数可以将:class:geoalchemy2.types.SpatialElement转换为Shapely几何图形。

在Item类中:

from geoalchemy2.shape import to_shape

point = to_shape(self.geo)

return {
    'latitude': point.y,
    'longitude': point.x
}

0

点类型语法是

Point ( Lat, Long)  

所以基本上根据 mosi_kha 的答案,返回值应该是:

from geoalchemy2.shape import to_shape

point = to_shape(self.geo)

return {
    'latitude': point.x,
    'longitude': point.y
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接