GeoAlchemy2 store point and query results

删除回忆录丶 提交于 2019-12-08 01:26:37

问题


The documentation on GeoAlchemy2 doesn't seem fully featured (as compared to the pervious version).

I have a model:

class AddressCode(Base):
    __tablename__ = 'address_codes'
    id = Column(Integer, primary_key=True)
    code = Column(Unicode(34))
    geometry = Column(Geometry('POINT'))

And I want to store lat/long data, which I tried to save in the above model, example

"51.42553,-0.666085"

Which gives me the error:

"Parse error at position 9 within Geometry (the "," char")

Anyone able to shed some light on where I am going wrong here?

Also on the subject, how would I peform a query to say..

Show nearest 20 users:

class AddressCode(Base):
    __tablename__ = 'address_codes'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(34))
    geometry = Column(Geometry('POINT'))

Something like?

geom_var = "51.42553,-0.666085"
Session.query(User).filter(func.ST_DWithin, 20, geom_var).all()

回答1:


In both GeoAlchemy and GeoAlchemy2 you need to specify the geometries in the well-known text format called WKT or Well-known text, or the Well-known binary format. For a point the syntax is 'POINT(X Y)', thus 'POINT(-0.666085 51.42553)' notice that the longitude comes first, then latitude.

The shapely module contains useful functions for handling geometries outside relational databases, along with easy conversions between Python geometry classes and WKT, WKB formats.




回答2:


Here's how you do it:

this region table is defined as:

regionTable = Table('region', metadata, Column('region_id', Integer, Sequence('region_region_id_seq'), primary_key=True), Column('type_cd', String(30)), Column('region_nm', String(255)), Column('geo_loc', Geography ) )

how to query it:

(give me all regions within 50 miles of my current location..)

sqlstring = select([regionTable], func.ST_DWithin(regionTable.c.geo_loc, 'POINT(-74.78886216922375 40.32829276931833)', 1609*50 ))

result = connection.execute(sqlstring)

            for row in result:
                    print "region name:", row['region_nm']


来源:https://stackoverflow.com/questions/19894692/geoalchemy2-store-point-and-query-results

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