我正在使用ruby geocoder gem按位置搜索。我想将搜索限制在已正式启动的位置。如果有人通过zip搜索,使用正则表达式很容易。但如果有人按城市搜索,我需要将城市转换成邮政编码,检查我的邮政编码表,如果是肯定的,则返回搜索结果。
geocoder api有一个反向地理编码部分:
reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
obj.city = geo.city
obj.zipcode = geo.postal_code
obj.country = geo.country_code
end
end
after_validation :reverse_geocode
这显然是为了在模型中使用而构建的。但我试图在我的控制器中使用它,但是obj.zipcode根本不起作用。 Geocoder.search('san jose,ca')似乎回归了我需要的东西,我只是不知道如何去做。这就是我所在的地方:
if params[:search].present?
# coords = Geocoder.coordinates(params[:search])
zip = Geocoder.search(params[:search])
if Zip.where(:zip => (params[zip.zipcode]), :launch => true).exists?
addresses = Address.near(params[:search], 25, :order => :distance)
@profiles = addresses.map{ |ad| ad.profile }.uniq unless addresses.nil?
@title = "Addresses Near " + (params[:search]).to_s
else
if Zip.where(:zip => (params[zip.zipcode]), :nearlaunch => true).exists?
addresses = Address.near(params[:search], 25, :order => :distance)
@profiles = addresses.map{ |ad| ad.profile }.uniq unless addresses.nil?
@title = "We have not launched for your location but these are near by " + (params[:search]).to_s
else
redirect_to :controller => 'pages', :action => 'notlaunched'
end
end