GeoAlchemy ST_DWithin实现

时间:2014-06-01 14:47:19

标签: python sqlalchemy postgis flask-sqlalchemy

嗨!我需要使用GeoAlchemy实现一个查询,以获得给定点附近的所有点(例如,在半径10米范围内)。对于存储点,我在PostGIS数据库中使用Geography字段。从SQLAlchemy文档中我发现我需要使用ST_DWithin函数,但我并不完全确定如何在Flask应用程序中实现此函数。

以下是相关的代码段:

# models.py
class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    location = db.Column(Geography(geometry_type='POINT', srid=4326))

#routes.py
from models import Post

@app.route('/get_coordinates')
    lat = request.args.get('lat', None)
    lng = request.args.get('lng', None)

    if lat and lng:
        point = WKTElement('POINT({0} {1})'.format(lng, lat), srid=4326)
        # Here i should make the query to get all Posts that are near the Point 

非常感谢你的时间!

1 个答案:

答案 0 :(得分:5)

经过一番研究,我成功地实现了以下查询:)

posts = db.session.query(Post).filter(func.ST_DWithin(Post.location, point, 10))