Add geocoder
to the Gemfile first:
Now let's update the Address
model, as follows:
class Address include Mongoid::Document include Geocoder::Model::Mongoid field :street, type: String field :zip, type: Integer field :city, type: String field :state, type: String field :country, type: String field :coordinates, type: Array belongs_to :location, polymorphic: true geocoded_by :formatted_addr after_validation :geocode def formatted_addr [street, city, state, country].join(',') end end
Now let's save some addresses. Execute the following commands:
irb> a = Author.new(name: "Gautam Rege")
=> #<Author _id: 4fbf4c78fed0ebcdd0000004, _type: "Author", name: "Gautam Rege">
irb > a.address = Address.new(street: "102 Union Street", city: "Pasedena", state: "CA", country: "US")
=> #<Address _id: 4fbf4caffed0ebcdd0000006, _type: "Address", street: "102 Union Street", zip: nil, city: "Pasedena", state: "CA", country: "US", coordinates: nil, location_type: "Author", location_id: BSON::ObjectId('4fbf4c78fed0ebcdd0000004')>
irb> a.save
=> true
irb> a.address
=> #<Address _id: 4fbf4caffed0ebcdd0000006, _type: "Address", street: "102 Union Street", zip: nil, city: "Pasedena", state: "CA", country: "US", coordinates: [-118.1481163, 34.1467468], location_type: "Author", location_id: BSON::ObjectId('4fbf4c78fed0ebcdd0000004')>
irb> a.address.coordinates
=> [-118.1481163, 34.1467468]
When we use geocoder
gem, we have set up an after_validation
callback. When the object is validated, we look up the geocoder, fetch its coordinates and save them in the object.
The geocoder
gem has various lookup services that it can refer to, such as Google Map APIs, Yahoo! Maps, Bing, FreeGeoIP, among others and it defaults to Google — you can configure these lookups yourself.
Suppose you enter an unknown address and the service cannot find the geolocation, it returns and does not update the coordinates-you're on your own then!
3.16.255.126