我有一个 Rails 模型,它使用 PostGIS POINT
类型来存储位置的坐标。如何查询边界框内包含的所有位置?边界框来自 Google map ,如下所示:
/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?*** )
}
最佳答案
使用 rgeo gem:
gem 文件:
gem 'rgeo'
模型.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
请注意,工厂 point
方法的参数顺序是 (lon, lat)。
您可能需要使用包含 rgeo 的 activerecord-postgis-adapter
gem。
关于ruby-on-rails - 使用 PostGIS 和 Rails 查找边界框内的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287260/