Last Update: Tue Mar 27 22:12:13 EDT 2007


acts_as_geocodable is a plugin to help build geo-aware applications. It automatically geocodes your models when they are saved, giving you the ability to search by location and calculate distances between records.


  event = Event.create :street => "777 NE Martin Luther King, Jr. Blvd.",
    :locality => "Portland", :region => "Oregon", :postal_code => 97232

  event.geocode.latitude                                #=> 45.529100000000
  event.geocode.longitude                               #=> -122.644200000000

  event.distance_to "49423"                             #=> 1807.66560483205

  Event.find(:all, :within => 50, :origin => "97232")

  Event.find(:nearest, :origin => "Portland, OR")


If you’re upgrading from a previous version of this plugin, note that :city has been renamed to :locality to be consistent with Graticule 0.2. Create a migration that has:

  rename_column :geocodes, :city, :locality

Also remember to change your mapping in your geocodable classes to use the :locality key instead of :city:

class Event < ActiveRecord::Base

        acts_as_geocodable :address => {:street => :address1, :locality => :city,
          :region => :state, :postal_code => :zip}



Graticule is used for all the heavy lifting.

  gem install graticule --include-dependencies

Install the plugin

  script/plugin install -x


Create the required tables

  script/generate geocodable_migration add_geocodable_tables
  rake db:migrate

Set the default geocoder in your environment.rb file.

  Geocode.geocoder = Graticule.service(:yahoo).new 'your_api_key'

Then, in each model you want to make geocodable, add acts_as_geocodable.

  class Event < ActiveRecord::Base

The only requirement is that your model must have address fields. By default, acts_as_geocodable looks for attributes called street, locality, region, postal_code, and country. To change these, you can provide a mapping in the :address option:

  class Event < ActiveRecord::Base
        acts_as_geocodable :address => {:street => :address1, :locality => :city, :region => :state, :postal_code => :zip}

If that doesn’t meet your needs, simply override the default to_location method in your model, and return a Graticule::Location with those attributes set.

acts_as_geocodable can also update your address fields with the data returned from the geocoding service:

  class Event < ActiveRecord::Base
        acts_as_geocodable :normalize_address => true

IP-based Geocoding

acts_as_geocodable adds a remote_location method in your controllers that uses to guess remote users location based on their IP address.

  def index
    @nearest = Store.find(:nearest, :origin => remote_location) if remote_location
    @stores = Store.find(:all)

Keep in mind that IP-based geocoding is not always accurate, and often will not return any results.


The source code is available at:

Patches and suggestions are welcome!

To Do

  • Documentation!!!
  • configurable formulas