-
Alex Reisner authoredAlex Reisner authored
Geocoder¶ ↑
Geocoder is a complete geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (find street address based on given coordinates), and distance calculations for ActiveRecord objects. It’s as simple as calling geocode
on your objects, and then using a scope like Venue.near("Billings, MT")
. Since it does not rely on proprietary database functions finding geocoded objects in a given area works with out-of-the-box PostgreSQL, MySQL, and even SQLite.
Compatibility¶ ↑
Geocoder has been successfully tested with Ruby (MRI) 1.8.7, 1.9.2, and JRuby 1.5.3.
Geocoder is compatible with Rails 3. If you need to use it with Rails 2 please see the rails2
branch (no longer maintained, limited feature set).
Geocoder also works outside of Rails but you’ll need to install either the json
(for MRI) or json_pure
(for JRuby) gem.
Install¶ ↑
As a Gem¶ ↑
Add to your Gemfile:
gem "geocoder"
and run at the command prompt:
bundle install
Or As a Plugin¶ ↑
At the command prompt:
rails plugin install git://github.com/alexreisner/geocoder.git
Configure Object Geocoding¶ ↑
Required Attributes¶ ↑
ActiveRecord: Your object must have two attributes (database columns) for storing latitude and longitude coordinates. By default they should be called latitude
and longitude
but this can be changed (see “More on Configuration” below):
rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float rake db:migrate
For reverse geocoding your model must provide a method that returns an address. This can be a single attribute, but it can also be a method that returns a string assembled from different attributes (eg: city
, state
, and country
).
Model Behavior¶ ↑
In your model, tell Geocoder which method returns your object’s full address:
geocoded_by :full_street_address # can also be an IP address after_validation :geocode # auto-fetch coordinates
For reverse geocoding, tell Geocoder which methods return latitude and longitude:
reverse_geocoded_by :lat, :lon after_validation :reverse_geocode # auto-fetch address
If you have just added geocoding to a class and have a lot of existing objects you can use this Rake task to geocode them all:
rake geocode:all CLASS=YourModel
Location-Aware Database Queries¶ ↑
To find objects by location, use the following scopes:
Venue.near('Omaha, NE, US', 20) # venues within 20 miles of Omaha Venue.near([40.71, 100.23], 20) # venues within 20 miles of a point Venue.geocoded # venues with coordinates Venue.not_geocoded # venues without coordinates