Search for hotels within a given radius for the locations of the corresponding objects (Gem Geocoder)

I have 3 tables: Objects , Locations , Hotels .

Each object has multiple locations, and each location has several hotels (20 miles by default radius).

My models (simplified it a bit to focus on the main things)

object.rb

 attr_accessible :name has_many :locations has_many :hotels 

location.rb

 attr_accessible :name, :address, :longitude, :latitude has_many :objects has_many :hotels 

hotels.rb

 attr_accessible :name, :address, :longitude, :latitude has_many :objects has_many :locations 

I want to create a search form where the user can enter Object name and search radius .

The exit should be a list of all hotels located within a given radius (less than or equal to 20 miles) from the center of each place, which corresponds to the object.

I want to use the geocoding gem method , but I'm not sure how to build the controller level of such a task.

enter image description here

+4
source share
1 answer

You want your db to program a spatial request-request for these requests, for example. MongoDB or PostGIS (in Postgres). I think the answer you are looking for will depend on which one you use. I use PostGIS for this and I really like it.

However, Geocoder can be used to power inside the system without a spatial query mechanism, although it will not be as efficient. If you get really big, it will stop. If you look at the source: https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/stores/active_record.rb

 # skeleton for the controller method obj = Object.find(name) locations = obj.locations near_hotels = locations.map do |loc| locations.hotels.near([loc.latitude, loc.longitude]) end 

Not sure if the near method accepts the radius argument correctly, but you can easily write your own by simply copying it:

 # on the hotel class def nearby(lat, lon, radius) options = self.send(:near_scope_options, lat, lon, radius, {}) select(options[:select]).where(options[:conditions]). order(options[:order]) } 

I highly recommend you check out PostGIS.

Note that my sample method creates a relation. You can narrow your choice by specifying only those hotels that match your property.

+3
source

All Articles