Search code examples
ruby-on-railsgoogle-mapsturbolinks

Rails 4: Google Maps not displaying


I'm trying to display a simple Google Map on my Rails 4 app. I chose to include the code statically for now until I get it to work. In my _head.html.erb partial, I have:

<head>
  <title><%= content_for?(:title) ? yield(:title) : t('website.name') %></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
  <%= yield(:google_maps_api) if content_for?(:google_maps_api) %>
  <%= csrf_meta_tags %>
</head>

Then in another view, I have a partial called _google_map.html.erb that does the following:

<% content_for(:google_maps_api) do %>
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=xyz&sensor=false" %>
<script type="text/javascript">
    function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
      zoom: 8
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>
<% end %>

<div id="map-canvas" style="width: 100%; height: 100%"></div>

When I look at the source, the js and div are getting properly output to the page. However, no map is displayed. Please note that I do have the following in my application.js file

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .

Any idea why the map is not being displayed? Thanks!


Solution

  • If the div is getting filled it but just isn't visible you may want to check the height. For the height: 100% to work it needs to be in a container that has a specific height. To see if the height is the problem, try something like:

    <div id="map-canvas" style="width: 400px; height: 400px"></div>