使用PostGIS和Rails查找边界框内的所有项目

Avi*_*hai 7 gis postgresql postgis ruby-on-rails

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

/locations?within=40.766159%2C-73.989786%2C40.772781%2C-73.979905&per_page=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?*** )
  }
Run Code Online (Sandbox Code Playgroud)

tee*_*tee 7

使用rgeo gem:

的Gemfile:

gem 'rgeo'
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

请注意,工厂point方法的参数顺序是(lon,lat).

您可能想要使用activerecord-postgis-adaptergem,其中包括rgeo).