我正在使用 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
这显然是为了在模型中使用而构建的。但是我试图在我的 Controller 中使用它,但是 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
最佳答案
试试 Area gem .你可以这样做:
"San Jose, CA".to_zip #=> ["95101", "95102", ...
关于ruby-on-rails - 用于查找邮政编码的 Ruby Geocoder gem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8935011/