GeoAlchemy2: Get the lat, lon of a point

妖精的绣舞 提交于 2019-12-22 13:44:08

问题


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?


回答1:


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)



回答2:


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
        }


来源:https://stackoverflow.com/questions/33482653/geoalchemy2-get-the-lat-lon-of-a-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!