Ruby Geocoder gem to find postal code

放肆的年华 提交于 2020-01-03 18:51:47

问题


I'm using the ruby geocoder gem to search by location. I want to limit searches to locations that have officially launched. If someone searches by zip, this is easy using a regex. But if someone searches by city, I need to convert the city into a zip code, check my zip table and if positive, return the search results.

The geocoder api has a section for reverse geocoding:

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

This is obviously built just for using in the model. But I'm attempting to use it within my controller, but obj.zipcode is not working much at all. Geocoder.search('san jose, ca') seems to return what i need, i just don't know how to get to it. Here's where I'm at:

  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

回答1:


Try the Area gem. You could do something like:

"San Jose, CA".to_zip #=> ["95101", "95102", ...



回答2:


You can use like this to get the zipcode for any latitude and longitudes

Geocoder.search([latitude, longitude]).first.postal_code

This you can use in controller or any files other than models. But geocoder also provides automatic conversions provides the table should have the column names required. For more info visit here geocoder



来源:https://stackoverflow.com/questions/8935011/ruby-geocoder-gem-to-find-postal-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!