在GeoAlchemy和PostGIS中查找最近的位置

问题描述

我正在尝试做一个简单的查询,在其中找到离用户最近的位置(在我的示例中,我正在使用机场)。数据库记录如下所示:

id: 2249
city: Osaka
country: Japan
location_type_id: 16
geolocation: SRID=4326;POINT(34.59629822 135.6029968)
name: Yao Airport

我的数据库查询如下:

@classmethod
  def find_nearest_locations(cls,data):
    self = cls(data)
    return db.session.query(LocationModel.location_type_id==16). \
      order_by(Comparator.distance_centroid(LocationModel.geolocation,func.Geometry(func.ST_GeographyFromText(self.__format_geolocation())))).limit(self.result_quantity)

不幸的是,我的函数不断返回空列表。我对GeoAlchemy不太熟悉,因为这是我第一次使用它。任何帮助将不胜感激。

谢谢。

解决方法

在Postgis中,必须首先将坐标表示为经度,然后再表示纬度。

您将需要在输入中交换坐标

geolocation: SRID=4326;POINT(34.59629822 135.6029968) 应该变成geolocation: SRID=4326;POINT(135.6029968 34.59629822)

,

我能够解决此问题。长话短说,由于我使用的是Flask-SQLAlchemy而不是常规的SQLAlchemy,因此我必须搜索LocationModel而不是db.session.query。代码看起来像这样。

@classmethod
  def find_nearest_locations(cls,data):
    self = cls(data)
    return LocationModel.query.filter(LocationModel.location_type_id==self.location_type_id). \
      order_by(Comparator.distance_centroid(LocationModel.geolocation,func.Geometry(func.ST_GeographyFromText(self.__format_geolocation())))).limit(self.result_quantity)