Skip to content

Instantly share code, notes, and snippets.

@ocxo
Created April 11, 2011 17:24
Show Gist options
  • Save ocxo/913894 to your computer and use it in GitHub Desktop.
Save ocxo/913894 to your computer and use it in GitHub Desktop.
require 'geocoder'
class Location
include Mongoid::Document
include Geocoder::Model::Mongoid
field :user_defined_location
field :lat, :type => Float
field :lon, :type => Float
field :coordinates, :type => Array
index :coordinates
field :full_street_address
field :street_address
field :street_number
field :street_name
field :premise
field :subpremise
field :political_neighborhood
# colloquial area throws strange error about string-int conversions
# field :colloquial_area, type => Integer
field :locality
field :sublocality
field :township
field :postal_code
field :city
field :county
field :state
field :state_code
field :country_name
field :country_code
key :full_street_address
belongs_to :neighbor
attr_accessible :user_defined_location
validate :user_defined_location, :presence => true
geocoded_by :user_defined_location, :coordinates => :coordinates, :latitude => :lat, :longitude => :lon
reverse_geocoded_by :coordinates do |location, results|
if geo = results.first
location.lat = geo.latitude
location.lon = geo.longitude
location.coordinates = geo.coordinates
location.full_street_address = geo.address
location.street_address = geo.street_address
location.street_number = geo.street_number
location.street_name = geo.street_name
location.premise = geo.premise
location.subpremise = geo.subpremise
location.political_neighborhood = geo.political_neighborhood
# location.colloquial_area = geo.colloquial_area
location.locality = geo.locality
location.sublocality = geo.sublocality
location.township = geo.township
location.postal_code = geo.postal_code
location.city = geo.city
location.county = geo.county
location.state = geo.state
location.state_code = geo.state_code
location.country_name = geo.country
location.country_code = geo.country_code
end
end
after_validation :geocode, :reverse_geocode,
:if => lambda{ |obj| obj.user_defined_location_changed? }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment