DEV Community

yaalese1
yaalese1

Posted on

How to use Geocoder Gem for A Rails Back end and React Front End

While working with my partner on our ruby on Rails phase 4 project we used MapBox Gl api to allow us to generate addresses and render it on a map. But we hit a wall because our map only works with coordinates lng and lat. We needed something to transform addresses into coordinates. With some research we found geocoder.

Geocoding is the process of transforming a description of a location — such as a pair of coordinates, an address, or a name of a place to a location on the earth’s surface.

*Geocoder gem * is a geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (finding street address based on given coordinates), and distance queries.

how to install Geocoder

gem install geocoder
Enter fullscreen mode Exit fullscreen mode

after installing you want to open up your Rails console
and check to see if you have received coordinates

Image description

Using rails resource you want to make a locations or places table with no association that holds your coordinates . Then seed and migrate your database use use Geocoder to collect the latitude and longitude for each address and add this to our empty lat/long database columns.

*Geocode our objects *
you will need to add geocoded_by :address to your model.

Class Location < ActiveRecord::Base 
  geocoded_by :address 
end
Enter fullscreen mode Exit fullscreen mode

This tells Geocoder that we will be using a method called #address to run the geocode, next we need to do is set up our method.

Class Location < ActiveRecord::Base 
  geocoded_by :address 
  def address 
    [street, city, state, country].compact.join(", ") 
  end 
end




Enter fullscreen mode Exit fullscreen mode

We can use .compact to leave out any columns that may be nil and then we will convert our array to a string by joining each item at the comma with .join(", ").

Now create a call back geocode method (this can be any thing) which will be used on our locations to receive our needed longitude and latitude.

Class Location < ActiveRecord::Base 

  geocoded_by :address 
  After_validation :geocode 
  def address 
    [street, city, state, country].compact.join(", ") 
  end 
end
Enter fullscreen mode Exit fullscreen mode

You will simply call location.geocode and it will return a latitude/longitude array. similar to our pervious example in the rails console

Top comments (0)