Ask A Question


You’re not receiving notifications from this thread.

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

Neil Patel asked in Rails

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

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?

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 %>
  <% end %>

** updated routes**

Rails.application.routes.draw do

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

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)
@locations = Location.all.order("created_at DESC")

when i run the app i search for m20 2wz and in my browser i get
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(‘, ‘)


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">]>


Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,969+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.