- 'rubygems'
- 'google_geocode'
gem install google-geocodedocumentation
Now when ever the user tries to save the address we can have a callback associated with it..
So in the users model we would define
before_save :calculateCoordinates
def calculateCoordinates
- catch(:done) do
- fullAddress = address+','+city+','+state+','+zip
- loc = Geocode.lookup(fullAddress)
- if loc
- puts "calculated geocode"
- self.lat = loc[:latitude]
- self.lon = loc[:longitude]
- else
- puts "Unable to calculate the geocode"
- end
- end
The hash that is returned is used to populate the user's model lat and lon methods before saving to the database.
If the code is unable to calculate the geo-code we can take necessary action in the else part.
The catch here is that I have refactored the code and use a Geocode class to do my ugly geo-code calculation. The file that contains my geocode class is /app/model/geocode.rb
- class Geocode < ActiveRecord::Base
- require 'rubygems'
- require 'google_geocode'
- def self.lookup(location)
- g = GoogleGeocode.new GOOGLE_GEO_API_KEY
- begin
- location = g.locate location
- {:latitude => location.latitude, :longitude => location.longitude}
- rescue GoogleGeocode::AddressError
- return false
- end
- end
- end
The lookup class method would return a hash containing the latitude and longitude when it is able to calculate the geo code or false when it encounters a problem while calculate the geo code for the bad address.
The GOOGLE_GEO_API_KEY is obtained by registering here