Search code examples
ruby-on-railsrubyreverse-geocodingrails-geocoder

Geocoder Gem Reverse Geocoding


After watching RailsCasts #273 I want to use the Geocoder gem. I've seen this:

class Skatepark < ActiveRecord::Base
  reverse_geocoded_by :latitude, :longitude
  after_validation :fetch_address
  ...
end

which will reverse geocode the coordinates and populate :address with formatted_address.

Can I get this separated as :street, :locality, :region, :country, and :postal_code from the geocoder gem?


Solution

  • I don't know your model but this is how you populate it. It's also documented in the page you referred to.

    class Skatepark < ActiveRecord::Base
      reverse_geocoded_by :latitude, :longitude do |obj, results|
        if geo = results.first
          # populate your model
          obj.city    = geo.city
          obj.zipcode = geo.postal_code
          obj.country = geo.country_code
        end
      end
      after_validation :fetch_address
      ...
    end