将 google maps javascript 标记添加到布局标题中
为了让 Google 地图能够与 turbolinks 正常工作,请将 javascript 标记直接添加到布局标题中,而不是将其包含在视图中。
# app/views/layouts/my_layout.html.haml
!!!
%html{:lang => 'en'}
%head
- # ...
= google_maps_api_script_tag
google_maps_api_script_tag
最好在帮助器中定义。
# app/helpers/google_maps_helper.rb
module GoogleMapsHelper
def google_maps_api_script_tag
javascript_include_tag google_maps_api_source
end
def google_maps_api_source
"https://maps.googleapis.com/maps/api/js?key=#{google_maps_api_key}"
end
def google_maps_api_key
Rails.application.secrets.google_maps_api_key
end
end
你可以使用谷歌注册你的应用程序,并在谷歌 API 控制台中获取你的 API 密钥。谷歌有一个简短的指南如何请求谷歌地图 javascript api 的 api 密钥 。
api 密钥存储在 secrets.yml
file 中:
# config/secrets.yml
development:
google_maps_api_key: '...'
# ...
production:
google_maps_api_key: '...'
# ...
不要忘记将 config/secrets.yml
添加到你的 .gitignore
文件中,并确保你没有将 api 密钥提交到存储库。