Skip to main content

how do i implement search by postcode/zipcode using the Geocoder Gem

Rails • Asked by Neil Patel

Building a small rails app that is able to search by postcode(zipcode) and radius, so it responds with contractors that are within that radius/postcode

schema.rb
create_table "locations", force: :cascade do |t|
t.string "company_name"
t.string "address"
t.string "city"
t.string "postcode"
t.float "latitude"
t.float "longitude"

Added the geocoder gem and updated the model

class Location < ApplicationRecord
geocoded_by :postcode
after_validation :geocode, :if => :address_changed?
end

when i add new locations it automatically gives me the latitude and longtitude of the location

in my index view i have added the search form

SubContractor Postcode search

  <p class="lead">Use this postcode search to quickly find subcontractors in your area</p>
  <p><%= form_tag locations_path, :method => :get do %>
    <%= text_field_tag :search, params[:search], placeholder: "e.g M20 2WZ" %>
    <%= submit_tag "Search Near", :name => nil %>
  </p>
  <% end %>

** updated routes**

Rails.application.routes.draw do

resources :locations, except: [:update, :edit, :destroy]
root 'locations#index'
end

and in my locations controller 

class LocationsController < ApplicationController

def index
@locations = Location.all
if params[:search].present?
@locations = Location.near(params[:search], 10, :order => :distance)
else
@locations = Location.all.order("created_at DESC")
end
end

when i run the app i search for m20 2wz and in my browser i get
http://localhost:3000/locations?utf8=%E2%9C%93&search=m20+2wz
but does not return any results ???

Also should my location.rb model be
geocoded_by :postcode or geocoded_by :address

or is it better to do
geocoded_by :full_address

def full_address
[address, city, postcode].compact.join(‘, ‘)
end


Hi Neil,

For all your locations, I'd geocode them by full address. If you geocode by just the postcode then you're going to get the coordinates of that zip code, not necessarily the coordinates of the building that location represents.

After you've verified that the coordinates are correct for your locations, you then can load up the rails console and try to manually get the results... so something like Location.near("M20 2WZ", 50) should give you some results at this point.


Location.near("M20 2WZ", 15) now shows
id: 9, company_name: "Winton Flooring Ltd", address: "46 Bury Old Rd, Whitefield", city: "manchester", postcode: "M45 6TL", latitude: 53.53980319999999, longitude: -2.2820915, created_at: "2017-07-11 10:32:46", updated_at: "2017-07-11 10:32:46">]>

Thanks!


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.