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.

Step-1: 
Lets Start by Creating a rails Application AlienFinder
terminal
$ rails new AlienFinder

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

Step-3:
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.
terminal
$ 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.
/Gemfile
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.
/app/models/alien.rb
class Alien < ActiveRecord::Base
  geocoded_by :address #can also be an IP address
  after_validation :geocode
end
The geocode method sends a request to an external API, by default the Google Maps API.

Step-6:
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.
/app/models/alien.rb
class Alien < ActiveRecord::Base
  geocoded_by :address
  after_validation :geocode, :if => :address_changed?
end

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.
/app/views/aliens/index.html.erb
<div class="centered">
  <h1>Alien Finder</h1>
  <%= form_tag aliens_path, :method => :get do %>
    <p>
      <%= text_field_tag :search, params[:search],:id => 'geo-input' %>
      <%= submit_tag "Search Near", :name => nil %>
    </p>
  <% end %>
  <h3>Nearby Aliens</h3>
  <% @aliens.each do |alien| %>
    <p>
      <div class="res">
      <b><%= alien.name %></b></br>
         <%= alien.address %></br>
          <%= alien.distance.round(2) %> miles
      </div>
    </p>
  <% end %>
</div>
and in controller
/app/controllers/aliens_controller.rb
def index
  if params[:search].present?
    @aliens = Alien.near(params[:search])
  else
    @aliens = Alien.all
  end
end
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.
/app/assets/javascript/applicaion.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require jquery.geocomplete
$(function() {
$("#geo-input").geocomplete();
});  

In application.html.erb add following lines
/app/views/layouts/application.hrml.erb
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
<script src="jquery.geocomplete.js"></script> 

Now you can see it working.
Reference RailsCast

3 comments:

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete

Followers