Saturday, 18 July 2015

Location Autocomplete and Geocoding using Google APIs in Rails

Location Autocomplete and Geocoding using Google APIs in Rails

Geocoder and rails autocomplete

Hello friends, Today we are going to make a web app that will help you find Aliens near your location. We will use Google Place API, GeocoderGem & Geocomplete jQuery plugin in this tutorial. 

GeoCoder Gem: If you have to work with Geographic data in your Rails applications the Geocoder gem makes this much simpler. It can convert place names to coordinates and vice-versa and even convert IP addresses to street addresses. It can also find nearby locations with their distance and bearing and has many other useful features. 

AutoComplete with GeoComplete: It is an advanced jQuery plugin that wraps the Google Maps API's Geocoding and Places Autocomplete services. You simply provide an input that lets you search for locations with a nice autocomplete dropdown. Optionally add a container to show an interactive map and a form that will be populated with the address details.

Lets Start by Creating a rails Application AlienFinder
$ rails new AlienFinder

Once we have created the application the next thing to do is to create an Alien scaffold with name, address, latitude and longitude fields.
$ rails g scaffold Alien name:string address:string latitude:float longitude:float

The naming of the latitude and longitude fields is important as Geocoder will use these to store the location coordinates, although the default field names can be overridden. Both fields need to be floats. We’ll need to migrate the database to create the new aliens table.
$ rake db:migrate

Step-4: Installing Geocoder
Now we have the scaffolding set up we can create new Aliens in our database but we have to enter the latitude and longitude manually. We’ll update our application now so that these fields are filled in automatically by Geocoder.
Add Geocoder in gemfile and run bundle command.
gem 'geocoder'

Step-5: Using Geocoder
Next we’ll modify our Alien model and add a call to geocoded_by to specify the attribute that we want Geocoder to convert, in this case the address.
class Alien < ActiveRecord::Base
  geocoded_by :address #can also be an IP address
  after_validation :geocode
The geocode method sends a request to an external API, by default the Google Maps API.

The external API will be called every time we update an alien but this should only happen when the address field changes. We can make a simple change to the after_validation callback to implement this.
class Alien < ActiveRecord::Base
  geocoded_by :address
  after_validation :geocode, :if => :address_changed?

Step-7:Getting nearby locations

We have a number of aliens in our database now so we’ll add this feature to our alien page.
We want to list each alien within a given distance and Geocoder makes getting nearby aliens easy with its nearbys method. By default this will return alien objects within a twenty-mile radius, but we can change it. To list the nearby aliens we just loop through each alien in @alien.nearbys and its distance in miles.
We will also add Search box where user can search for aliens near an address.
<div class="centered">
  <h1>Alien Finder</h1>
  <%= form_tag aliens_path, :method => :get do %>
      <%= text_field_tag :search, params[:search],:id => 'geo-input' %>
      <%= submit_tag "Search Near", :name => nil %>
  <% end %>
  <h3>Nearby Aliens</h3>
  <% @aliens.each do |alien| %>
      <div class="res">
      <b><%= %></b></br>
         <%= alien.address %></br>
          <%= alien.distance.round(2) %> miles
  <% end %>
and in controller
def index
  if params[:search].present?
    @aliens = Alien.near(params[:search])
    @aliens = Alien.all
Step-8: Autocomplete Address Search Box
Next we'll add Autocomplete feature in search box.
Download Geocmplete zip file HERE 
Extract it and copy jquery.geocomplete.js into app/assets/javascripts folder.
Now in application.js or alien.js add //= require jquery.geocomplete and following function.
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require jquery.geocomplete
$(function() {

In application.html.erb add following lines
<script src=";libraries=places"></script>
<script src="jquery.geocomplete.js"></script> 

Now you can see it working.
Reference RailsCast


  1. couldn't find file 'jquery.geocomplete' with type 'application/javascript' in rails 5

  2. You need to download geocomplete from github and add it to your rails project.

    I needed this so much a week ago but figured it with some Google help

  3. I am getting following error

    ActionController::RoutingError (No route matches [GET] "/jquery.geocomplete.js"):

    While I have places the file in app/assets/javascripts

  4. Thank you, it work for me.
    But i have just add key and libraries parameters:

  5. Google Sugession finder Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.