Find all elements framed with PostGIS and Rails

I have a Rails model that uses the PostGIS POINT type to store location coordinates. How can I request all the locations that are contained in the bounding box? The bounding box comes with Google Maps as follows:

/locations?within=40.766159%2C-73.989786%2C40.772781%2C-73.979905&per_page=500

then in my model I have the ability to handle this, but I can’t figure out how to get the request correctly:

 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?*** ) } 
+7
source share
1 answer

Using 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 can use the activerecord-postgis-adapter , which includes rgeo).

+5
source

All Articles