sqlalchemyflask-sqlalchemygeoalchemy2

How to order a geospatial query by distance from the query point


I try searching for this problem on the web, but to no avail. Seems like a basic task. I'm using PostGresql through SQLAlchemy with Geoalchemy to do geospatial queries. Technically, I'm using `Flask-SQLAlchemy. I can do a geospatial query. For example:

from geoalchemy2 import func
cls.db.session.query(cls).filter(func.ST_DWithin(cls.geoLoc, geo, meters))

where cls is the class I'm querying on. geo is the Geography point representing the center of the query and meters is the max distance to return results from. This query works, but returns results in an arbitrary order. I want them returned in increasing (decreasing is fine too) distance from the query point.

I assume I need to use an .order_by(...) at the end of the query, but I can't figure out what to put in there.


Solution

  • Alright, I figured it out, but wow that wasn't obvious, especially if you're not intimately familiar with Geoalchemy2.

    In my case above, you have to tack:

    .order_by(func.ST_Distance(cls.geoLoc, geo))
    

    to the end of the code that's in my question. Basically, ST_Distance is a function that takes in a two points and returns the distance between them. So cls.geoLoc refers to the each object in question from the table and geo is the center from which I'm sorting by distance. This basically computes the distance for each element to geo and then sorts by it.