Ruby Geocoder gem to find postal code

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

Answers


Try the Area gem. You could do something like:

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

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


Need Your Help

CREATE and DROP database won't work

sql database postgresql

I want simply drop some databases and after that create a new one.

PHP ajax with jquery slidedown

php jquery mysql ajax

i have a complicated PHP conundrum. I have a constantly updating table in my database (Lets call it TABLE) with multiple records being added a second, these results will be posted using PHP on a pa...