Search code examples
jqueryruby-on-rails-4turbolinksgmaps4rails2

First load time app loads using Gmaps4rails gem map won't load


I've been banging my head with this for 2 days now and have read every post on here and tried just about everything. Here is my JS, everything works after 1st page refresh but when launch new browser, fails first time map is called. I'm getting error:

Uncaught TypeError: Cannot read property 'addMarker' of undefined

Here is my code: I've tried so many different ways. Please can someone help me solve this!?

$(document).on("ready page:load", getDivData);

function getDivData(){
  var data = $('#gmap').data('mapdata');
  renderGoogleMap(data);
}

function renderGoogleMap(data) {
  var mapData = data;
  handler = Gmaps.build('Google');
  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
    markers = handler.addMarkers(mapData);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
    handler.getMap().setZoom(12);
  });
}

//= require jquery-2.1.1.min
//= require jquery-ui
//= require jquery_ujs
//= require_self
//= require autocomplete-rails
//= require twitter/bootstrap
//= require bootstrap-dark
//= require underscore
//= require events
//= require event_show
//= require turbolinks
//= require gmaps/google

In my HTML Header

  <title>MyApp</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
  <script src="//maps.google.com/maps/api/js?v=3.13&amp;sensor=false&amp;libraries=geometry" type="text/javascript"></script>
  <script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js' type='text/javascript'></script>


Solution

  • Found the error. The getDivData() function should only be called if var data returns true. Updated method:

    function getDivData(){
      var data = $('#gmap').data('mapdata');
      if(data){
        renderGoogleMap(data);
      }
    }