Add the Google Maps JavaScript tag to the layout header

suggest change

For Google Maps to work with Turbolinks, add the JavaScript tag in the layout header instead of in a view.

# app/views/layouts/my_layout.html.haml
!!!
%html{:lang => 'en'}
  %head
    - # ...
    = google_maps_api_script_tag

The google_maps_api_script_tag is best defined in a helper.

# 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

Register the application and get an API key in the Google API console. Google has a short guide to requesting an API key for the Maps JavaScript API.

Store the API key in secrets.yml:

# config/secrets.yml
development:
  google_maps_api_key: '...'
  # ...
production:
  google_maps_api_key: '...'
  # ...

Add config/secrets.yml to .gitignore so the API key is not committed. On Rails 5.2 and later, prefer encrypted credentials over secrets.yml.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents