drifter-rails

NOTE: this gem is no longer maintained because the rails-geocoder gem provides much the same functionality:

github.com/alexreisner/geocoder

drifter-rails is a simple gem that provides distance calculations and queries for ActiveRecord. It currently supports postgresql and mysql on rails 3.

Installation

# in Gemfile
config.gem 'drifter-rails'

# optionally, in config/intiailizers/drifter.rb, one of these:
Drifter.default_units = :miles
Drifter.default_units = :km

# in your model
class Place < ActiveRecord::Base
  acts_as_drifter
end

Usage

To return a calculated ‘distance’ value along with your queries:

>> origin = [52.123, -2.5432]
>> results = Place.near(origin)
>> results.first.distance
=> 12.33228393

origin can be a two item [lat,lng] array, any acts_as_drifter object or any object that responds to lat() and lng().

To return objects within a specific distance of a point of origin:

>> origin = [52.123, -2.5432]
>> Place.near(origin, :within => 10)
>> Place.near(origin, :within => 10, :units => :km)
=> "#<ActiveRecord::Relation:0xafb1e18>"

The near() method returns an ActiveRecord::Relation that you can use the same as any other scope, including ordering by distance:

>> Place.near(origin, :within => 10).includes(:visitors).order("distance ASC")
=> "#<ActiveRecord::Relation:0xafb1e18>"

Each acts_as_drifter object also gets a distance_to() method that can calculate the distance to another location:

>> place = Place.first
>> place.distance_to(other_place)
>> place.distance_to( [10.321, -5.432] )
>> place.distance_to( [10.321, -5.432], :units => :km )

The location() and location=() methods provide a shortcut for setting lat() and lng():

>> place = Place.new
>> place.location = [2.222, 3.333]

>> place.lat
=> 2.222
>> place.lng
=> 3.333

Finally, you can use custom names for the lat and lng columns:

class Place < ActiveRecord::Base
  acts_as_drifter :lat_column => :latitude, :lng_column => :longitude
end

License

MIT License. Copyright 2011 Ahmed Adam (github.com/ahmedrb)