parm530
8/28/2017 - 1:49 PM

Notes on using Geolocation and Search with Geocoder

Notes on using Geolocation and Search with Geocoder

Using Geocoder

  • Geocoder
  • ruby geocoder gem
  • Geocoding: taking an address and obtaining latitude and longitude
  • Reverse geocoding: taking a lat and lon and obtaining an address
  • Provides a database search for nearby locations --

STEPS:

  • Add to gemfile:
gem 'geocoder'
bundle install
  • In your database table, if you have columns for latitude and longitide and columns for address, city, state and zipcode, it is pretty easy for the gem to set up the lat and long fields
  • In your model class add this line of code:
  geocoded_by :address  # knows how to geocode your model
  • If your address isn't full (meaning that is separated by address, city, state, and zipcode columns) you'll need to combine them to form a full address
  • You can combine them using by defining the following method:
  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.
  • Let's update the after_validation:
  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
  • Comes with a way to make batch requests, using it's own rake task call:
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