Rails:redirect_to外部网址(谷歌地图)并传递参数

时间:2018-01-22 13:47:53

标签: ruby-on-rails google-maps google-maps-api-3

我的rails应用中有一项功能,我想重定向到Google方向网址(https://www.google.com/maps/dir/?api=1)并获取从当前位置到目的地的路线。我试图根据google maps API here实现此功能。不幸的是,这不起作用,它确实重定向到谷歌网址,但它没有通过参数,以便正确设置方向。

这是我的设置:

链接以及Google需要的参数才能使其正常工作:

<%= link_to 'Directions', initialize_path(:origin => @origin, :destination => @destination), method: :get %>

路线:

get 'initialize' => 'pages#initialize', :as => 'initialize'

该方法重定向到google网址并传递所需的参数:

def initialize
  redirect_to generate_url('https://www.google.com/maps/dir/?api=1',
                         { :origin=> params[:origin], :destination => params[:destination] })
end

帮助者:

def generate_url(url, parameters ={})
  uri = URI(url)
  uri.query = parameters.to_query
  uri.to_s
end

控制台显示参数不是零并且实际上正在传递:

`Started GET "/initialize?    destination=40.712775%2C-74.005973&origin=40.720341%2C-74.044847" for 127.0.0.1 at 2018-01-21 17:53:55 +0200
Processing by PagesController#initialize as HTML
Parameters: {"authenticity_token"=>"50liTLXVpXgGcLxEzFHRMZ0FNQ5eyvoAY8+qSb6LJ549BitH1Li91QcnKWggoQbzrdPrEDrotT2pVvEiDdiTAg==", "destination"=>"40.712775, -74.005973", "origin"=>"40.720341,-74.044847"}
Redirected to https://www.google.com/maps/dir/?destination=40.712775%2C-74.005973&origin=40.720341%2C-74.044847
Completed 302 Found in 0ms (ActiveRecord: 0.0ms)`

有关如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

我找到了一种更简单的方法:

<%= link_to "Directions", ('https://www.google.com/maps/dir/?api=1''&origin='+@origin+'&destination='+@destination) %>