如何在 rails 项目中使用 Geokit

How to use Geokit on a rails project

我正在使用 Rails 4.2.0 和 Ruby 2.2.0。我想使用 geokit 将地址转换为经纬度。我已经 gem 在我的终端中安装了 geokit。我还在我的 Gemfile 中包含 gem 'geokit',并且 运行 捆绑安装。

在控制器上,我尝试使用函数 Geokit::Geocoders::GoogleGeocoder.geocode()。

当我像这样使用它时,出现了这个错误:未初始化的常量AnswersController::Geocoders(我的控制器称为 Answers)

当我尝试在控制器的开头添加 require 'geokit' 时,出现错误:无法加载此类文件 --geokit.

你知道我可以做些什么来解决这个问题吗?

提前致谢

这是我的控制器

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

I already did gem install geokit in my terminal. I also included gem 'geokit' in my Gemfile, and run bundle install.

不需要两者都做。

按照以下步骤确保您已正确安装 geokit gem:

一个。在 Gemfile

中添加 geokit gem
# Gemfile
gem 'geokit'

b。 运行 bundle install;验证 gem 是否安装了 bundle show geokit

c。在 rails 控制台中尝试以下操作:

$ rails console
> a=Geokit::Geocoders::GoogleGeocoder.geocode '140 Market St, San Francisco, CA'
 => #<Geokit::GeoLoc:0x007fe877305c70 @all=[#<Geokit::GeoLoc:0x007fe877305c70 ...>], @street_address="140 Market Street", @sub_premise=nil, @street_number="140", @street_name="Market Street", @city="San Francisco", @state=nil, @state_code="CA", @state_name="California", @zip="94105", @country_code="US", @province="CA", @success=true, @precision="address", @full_address="140 Market Street, San Francisco, CA 94105, USA", @lat=37.793688, @lng=-122.3958692, @provider="google", @neighborhood="Financial District", @district="San Francisco County", @country="United States", @accuracy=8, @suggested_bounds=#<Geokit::Bounds:0x007fe8772fef60 @sw=#<Geokit::LatLng:0x007fe8772fef88 @lat=37.7923338697085, @lng=-122.3972116302915>, @ne=#<Geokit::LatLng:0x007fe8772ff050 @lat=37.7950318302915, @lng=-122.3945136697085>>> 
> a.ll
 => "37.793688,-122.3958692"

我想我找到了解决办法。代码很好,Prakash 发布的所有步骤都很好。

但是我需要在您完成 运行 那些步骤后在终端上重新启动 rails 服务器,这就是它无法在浏览器上运行的原因!现在可以使用了。

感谢大家的回答。我不知道这是否是最好的解决方案,但至少它有效。