June 3, 2017
Ruby on Rails Tutorial No Comments

Geolocation Rails Tutorial

Rails Tutorial for Geolocation. Geolocation is the process of getting the actual physical location of an object like mobile phone, computers or any other devices connected to internet. The location of user can enhance the marketing and recommendation. Also tracking people and getting to know if they reached the destination safely or tracking criminal activities would be really easy if we could build apps that support geolocation. Thanks to geolocation service provided by Google so that we can reach to places, we haven’t heard or gone before. We can find out restaurants, hotels, ATM machines, universities, bus stations etc around us even in the places we don’t know or we are new. All these can be done using geolocation.

Privacy is a major concern in this time. So building an application that tracks user’s location without letting them know is a crime. The user agents like web apps should ask for permission to the users before sending their location to the server. All of us have used the apps that asks user to get the location. We should share our location only if we trust the application.


Working Mechanism

Geolocation can be accessed by different methods. One is by using wireless connection through the nearest cell tower another is by using dedicated hardware that calculates latitude and longitude when information is sent from satellite to your hardware. Popular devices today uses triangulation technique that tries to get the rough idea of where the user’s location using the cell towers. The second method using the dedicated chip is more accurate but it draws lot of power.


What can you do with geolocation?

Geolocation specific information is very hot right now. There are many use cases for geolocation. Let me list few of them.

  • Show point of interest like ATM
  • Help travellers by calculating distances, cost of travelling
  • Navigate places
  • Solve how to reach problems
  • Track your health by calculating distance you walk
  • Personalize webpages to users of specific location
  • Calculate shipping cost for e-commerce store
  • Localization of languages for international sites
  • Real estate, hotel and location based service websites etc.


There are many wonderful things that you can do with geolocation.


Using geolocation API

Before using geolocation, your browser must support this feature. Most of the modern browsers these days support geolocation. Geolocation API given by Google map gives three methods:

  • getCurrentPosition() => Used to get the geolocation at a point of time
  • watchPosition() => Used if we need to get location continuously e.g while driving
  • clearWatch() => Clear the position

Since geolocation process is very complicated we also need to do some error handling. Now let’s see what information we can collect using geolocation API. If the geographical information is collected successfully using geolocation API using the above methods a function object is called with the position input parameter. The position object has two properties

  • Timestamp
  • Coordinates


Timestamp is nothing but the time when the geolocation is calculated. The coordinates property has number of objects that are really useful. Let me list them

  • Latitude ( float decimal number )
  • Longitude ( float decimal number )
  • Accuracy ( accuracy by which geolocation is calculated )
  • Altitude ( height above the sea level )
  • Altitude Accuracy ( accuracy by which the altitude is calculated )
  • Heading ( the direction in which the device is moving )
  • Speed ( the speed in which the device is moving )


Now let’s create a new file called mylocation.hml

<!DOCTYPE html>



   <title>Where Am I?</title>

   <script src=””></script>

     <script type=”text/javascript”>

         var watchId, geocoder, startLat, startLong;

         var start = 1;

         window.onload = function(){

             if (navigator.geolocation){

               watchId = navigator.geolocation.watchPosition(onSuccess, onError,{maximumAge:60*1000, timeout:5*60*1000, enableHighAccuracy:true});



         function onSuccess(position){

           var currentLat = position.coords.latitude;

           var currentLong = position.coords.longitude;

           if (start == 1){

             startLat = currentLat;

             startLong = currentLong;

             start = 0;



       var geocoder = new google.maps.Geocoder();

       var latlong = new google.maps.LatLng(currentLat, currentLong);


       geocoder.geocode({‘latLng’:latlong}, function(results, status){

         if (status == google.maps.GeocoderStatus.OK){

           if (results){

             document.getElementById(“location”).innerHTML = “You are now near ” + results[0].formatted_address;




           alert(“Could not get the geolocation information”);



         var mapOptions = {

           center: new google.maps.LatLng(startLat, startLong),

           zoom: 10,

           mapTypeId: google.maps.MapTypeId.ROADMAP



         var map = new google.maps.Map(document.getElementById(“mapArea”), mapOptions);

         var marker = new google.maps.Marker({

           position: latlong,

           map: map




function onError(error){



   alert(“User denied permission”);



   case TIMEOUT:

   alert(“Geolocation timed out”);




   alert(“Geolocation information is not available”);




   alert(“Unknown error”);







   <div id=”location”></div>

   <div id=”mapArea” style=”height:500px; width:500px”></div>



Save this page and put this file into the apache server’s root. If you try to open the file without having the server it won’t work.


Using Rails for geolocation

You have also a option of using a Ruby gem instead of the javascript code for fetching the api request. We have a gem called geocoder . You can use this gem for normal geocoding as well as reverse geocoding. You may need to get the geolocation API key for this purpose. Go to to get one. So add this gem to your project gemfile in Rails

gem ‘geocoder’


Then run the bundler. To install the gem.

Add column to the models where you want to add the geolocation feature. For example, you want to track the users, then create a user model with latitude and longitude as the columns.

$ rails g model User name:string email:string address:string latitude:float longitude:float


After this you need to run the migration

$ rails db:migrate


Next, we need a method that returns address in our model. Now in our model file user.rb make some changes like below


geocoded_by :address

after_validation :geocode



Let’s tweak a little bit for limiting the requests to API

$ after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }


We only need to geocode if the address is present or if the user has changed the address.

Now if we need to reverse geocode then the following callbacks should be added in the model file


reverse_geocoded_by :latitude, :longitude

after_validation :reverse_geocode  # auto-fetch address



You can also use Mongo db for geocoding. You can read more about configuring it



Geolocation apps are very hot right now. We have endless possibility with what we can do with geolocation and geocoder gem.