Ruby on rails 使用PostGIS和Rails查找边界框中的所有项目

Ruby on rails 使用PostGIS和Rails查找边界框中的所有项目,ruby-on-rails,postgresql,gis,postgis,Ruby On Rails,Postgresql,Gis,Postgis,我有一个Rails模型,它使用PostGIS点类型来存储位置的坐标。如何查询边界框中包含的所有位置?边界框来自谷歌地图,如下所示: /locations?在=40.766159%2C-73.989786%2C40.772781%2C-73.979905内&每页=500 然后,在我的模型中,我有一个范围来处理这个问题,但不知道如何获得正确的查询: scope :within, ->(box_string) { sw = box_string.split(",")[0..1].reve

我有一个Rails模型,它使用PostGIS
类型来存储位置的坐标。如何查询边界框中包含的所有位置?边界框来自谷歌地图,如下所示:

/locations?在=40.766159%2C-73.989786%2C40.772781%2C-73.979905内&每页=500

然后,在我的模型中,我有一个范围来处理这个问题,但不知道如何获得正确的查询:

scope :within, ->(box_string) {
    sw = box_string.split(",")[0..1].reverse.map {|c| c.to_f}
    ne = box_string.split(",")[2..3].reverse.map {|c| c.to_f}
    box = "BOX3D(#{sw[0]} #{sw[1]}, #{ne[0]} #{ne[1]})"
    where( ***WHAT DO I DO HERE?*** )
  }
使用rgeo gem:

档案:

gem 'rgeo'
model.rb:

def self.within_box(sw_lat, sw_lon, ne_lat, ne_lon)
  factory = RGeo::Geographic.spherical_factory
  sw = factory.point(sw_lon, sw_lat)
  ne = factory.point(ne_lon, ne_lat)
  window = RGeo::Cartesian::BoundingBox.create_from_points(sw, ne).to_geometry
  where("your_point_column && ?", window)
end
请注意,工厂
方法的参数顺序是(lon,lat)


您可能需要使用
activerecord postgis适配器
gem,其中包括rgeo)。

不使用
squel
怎么样?