ruby-on-railsrubygeokit

How to use Geokit on a rails project


I am using Rails 4.2.0 and Ruby 2.2.0. I want to use geokit to convert an address to latitude and longitude. I already did gem install geokit in my terminal. I also included gem 'geokit' in my Gemfile, and run bundle install.

On a controller, I try to use the function Geokit::Geocoders::GoogleGeocoder.geocode().

When I just use it like this, I got this error : uninitialized constant AnswersController::Geocoders (my controller is called Answers)

When I try to add require 'geokit' at the beginning of the controller, I got the error : cannot load such file --geokit.

Do you have any idea of what I could do to solve the problem ?

Thanks in advance

Here is my controller

require 'rubygems'
require 'geokit'
class AnswersController < ApplicationController
before_action :set_answer, only: [:show, :edit, :update, :destroy]
def render_page2
  render('page2')
end
def answer_page2
if params[:address_origin] && params[:address_destination]
  session[:lat_origin] = Geokit::Geocoders::GoogleGeocoder.geocode(params[:address_origin]).lat
  session[:lon_origin] = Geokit::Geocoders::GoogleGeocoder.geocode(params[:address_origin]).lng
  session[:lat_destination] = Geokit::Geocoders::GoogleGeocoder.geocode(params[:address_destination]).lat
  session[:lon_destination] = Geokit::Geocoders::GoogleGeocoder.geocode(params[:address_destination]).lng
  #session[:lat_origin] = 37.793688
  #session[:lon_origin] = -122.3958692
  #session[:lat_destination] = 37.866437
  #session[:lon_destination] = -122.265415
  redirect_to '/page3'
else
  flash[:message] = "All the questions are required on this page."
  redirect_to '/page2'
end
end
end

Solution

  • I think I found the solution. The code is good and all the steps posted by Prakash are good.

    But I needed to restart the rails server on the terminal after you run those steps, that is why it was not working on the browser ! Now it is working.

    Thanks everyone for your answers. I don't know if it is the best solution, but at least it works.