Notes on using Geolocation and Search with Geocoder
gem 'geocoder'
bundle install
geocoded_by :address # knows how to geocode your model
def address
[address, city, zipcode, state].compact.join(", ")
end
this creates the string needed for geocoder to obtain the long/lat fields
You may also need to use an after_validation method.
This method says that if this record is being saved, then go ahead and make sure its long and lat fields are accurate.
Will be run every single time you validate the object you don't want that, only when a field changes then you'll want to update it
To trigger the update for when certain fields are changed, there are active record methods called:
nameofcolumn_changed? to see if a column has changed values.
after_validation :geocode, if: :address_changed?
def address_changed?
address_changed? || city_changed? || zipcode_changed? || state_changed?
end
If one of these fields change, then the validation is tried and then the model objext is updated!
Useful for reducing the amount of API calls for geocoding!
You will need to generate the config file:
rails generate geocoder:config
rake geocode:all CLASS=yourmodelname SLEEP=0.25 BATCH=100
sleep means how long to wait before the next call (0.25 = a quarter of a second before hitting the API)
batch means how many records at once to update
To find a location of a place within your database, you can use the .near() method and pass in either a string of the location or an array contining the longitude and latitude
If you enter a string of the location. it will geocode that location and run some queries that will find nearby locations in your database