Search code examples
ruby-on-railsruby-on-rails-3gmaps4rails

Problems with Gmaps.map.replaceMarkers: Gmaps.map is undefined


I am trying to dynamically change the markers in Gmaps4Rails based on a user search form. I am using the code below.

The problem I am encountering is that the call to Gmaps.map.replaceMarkers within $('#locations_search').submit gives an error: Gmaps.map is undefined.

I checked using the javascript debbuger, and indeed once I enter the submit function (I have a breakpoint there), Gmaps.map is undefined. When stopping with a breakpoint in the first lines of Gmaps.map.callback, the object Gmaps.map is defined.

Probably I am missing something. It seems to be some variable scope problem here?

Gmaps.map.callback = function() {

  var firstMarker = Gmaps.map.markers[0];
  var map         = Gmaps.map.map;
  firstMarker.infowindow.open(map, firstMarker.serviceObject);

  $('#locations_search').submit(function () {
    var url = '/locations.json/?' + $(this).serialize();
    $.getJSON(url, function(data){
                Gmaps.map.replaceMarkers(data);
            });
    $.get(this.action, $(this).serialize(), null, 'script');
    return false;
  });
}

Thanks a lot!


Solution

  • It's just a question of script order.

    Gmaps.map is created in your view when You call either gmaps or gmaps4rails helpers.

    Solution:

    • Add your scripts after your call to the gem's helpers

    • wrap your js code in <% content_for :scripts do %> code <% end %>


    in your view:

    <%= gmaps(...) %>
    <% content_for :scripts do %>
    <script type="text/javascript"> 
      Gmaps.map.callback = function() { ... }
    </script>
    <% end %>
    

    Gmaps.map.callback = function() {
    
      var namespace   = Gmaps.map;
      var firstMarker = namespace.markers[0];
      var map         = namespace.map;
      firstMarker.infowindow.open(map, firstMarker.serviceObject);
    
      $('#locations_search').submit(function () {
        var url = '/locations.json/?' + $(this).serialize();
        $.getJSON(url, function(data){
                namespace.replaceMarkers(data);
            });
        $.get(this.action, $(this).serialize(), null, 'script');
        return false;
      });
    }