We know that the distance field gets dropped when using the Geokit gem in Rails with acts_as_mappable :through model class. I wonder if there's a way to work around this to get the distance field back. I tried to follow the monkey-patching example over here: http://www.sobyteme.com/news/2010/05/13/computers/2010/06/25/geokit-acts_as_mappable-through-with-distance-attribute/ but it didn't work for me.
Asked
Active
Viewed 870 times
1
-
I suggest you have a look at the gmaps4rails gem. – apneadiving May 15 '11 at 08:46
-
Unfortunately the gmaps4rails gem has nothing to do with the question that I've posted. They are really unrelated. – Anand Iyer May 18 '11 at 23:29
-
sorry, I thought `act_as_mappable` created a map – apneadiving May 19 '11 at 06:19
1 Answers
1
Well, Steve's suggestion over on his site was accurate, I was missing calling sort_by_distance_from after doing the find. So credit goes to him for this answer.
I'm on Rails v3.0.7. Here's my code:
class Office < ActiveRecord::Base
has_many :users
acts_as_mappable :default_units => :miles,
:default_formula => :sphere,
:lat_column_name => :latitude,
:lng_column_name => :longitude
end
class User < ActiveRecord::Base
belongs_to :office
acts_as_mappable :through => :office
end
users_controller.rb:
# Monkey patching to include the 'distance' attribute
module Geokit
module Mappable
def to_lat_lng
return self if instance_of?(Geokit::LatLng) || instance_of?(Geokit::GeoLoc)
return LatLng.new(self.office.send(self.office.class.lat_column_name),
self.office.send(self.office.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable)
nil
end
end
end
class UsersController < ApplicationController
def location
@lat = params[:lat].to_f
@long = params[:long].to_f
@origin = [@lat, @long]
@users = User.find(:all,
:origin => @origin,
:conditions => "distance < 3")
# We have to add this to get the 'distance' field
@users.sort_by_distance_from(@origin)
respond_to do |format|
format.html
format.xml { render :xml => @users.to_xml(:methods => :distance)}
format.json { render :json => @users.to_json(:methods => :distance)}
end
end
...
end

Anand Iyer
- 701
- 5
- 10