Thursday, December 13, 2007

Calculate GeoCode using google-geocode

To calculate the latitude and the longitude based on the address provided by the user we will have to use a couple of libraries namely
  • 'rubygems'
  • 'google_geocode'
To install it use the following command in your console
gem install google-geocode
documentation

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
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