Find all items within a bounding box with PostGIS and Rails
Using the rgeo gem:
Gemfile:
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
Note that the argument order for the factory point
method is (lon, lat).
You may want to use the activerecord-postgis-adapter
gem, which includes rgeo).