I’m using the Geocoder and Sunspot gem in my application and I have a field called :search_near_address that is suppose to give users the ability to input an address they want to search near within X amount of miles. What I am trying to map to is my Stores :address to use for the :search_near_address field. This way users can input an address ( i.e. 451 University Avenue, Palo Alto, CA ) in the :search_near_address field and it will search in a radius of 50 miles.
Answer
Sunspot 1.2.1
class Store < ActiveRecord::Base
attr_accessible :address, :latitude, :longitude
has_many :products
geocoded_by :address
after_validation :geocode
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode
end
class Product < ActiveRecord::Base
belongs_to :store
searchable do # Searching with product model.
string :search_near # For rake sunspot:reindex
location :location
end
def search_near_address
store.address if store # You may have to use the "if store".
end
def location
# may need the "if store" after longitude)....
Sunspot::Util::Coordinates.new(store.latitude, store.longitude)
end
end
class SearchController < ApplicationController
def index
@search = Product.search do |q| # Search with sunspot
q.fulltext params[:search]
q.with(:location).near(*Geocoder.coordinates(params[:search_near_address]), :precision => 4) if params[:search_near_address].present?
end
@products = @search.results # Return results from Product.search block.
end
end
# search/index/html.erb
<%= form_tag results_search_index_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= text_field_tag :search_near_address, params[:search_near_address] %>
<%= submit_tag "Go", :name => nil %>
<% end %>
First what @m_x said is right, you can’t expect assigning the Store#near results to the @search object would work….
Just reading the docs about Geospatial in https://github.com/sunspot/sunspot, you can clearly see that you are missing a few things:
You have to declare your Geospatial field using the latitude and longitude fields that geocoder requires:
Then you can search (after having indexed something) like this:
Also read about the :precision option here http://sunspot.github.com/docs/Sunspot/DSL/RestrictionWithNear.html#near-instance_method
About Geocoder https://github.com/alexreisner/geocoder