將 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 金鑰提交到儲存庫。