Search code examples
javascriptruby-on-railsgoogle-mapsgmaps4rails

How to initiate Gmaps in hidden element


I have one element (#hidden-element) which is hidden by default. When I click on button (#btn-toggle) I want to make this element visible. For now, everything is fine. The element really shows up, but if I click on the button for the first time, maps won't shows up. Then I click to hide element, then again to show hidden element for the second time and now the map is here.

So, my question is, how can I be shure that map will shows up for the first time (I thing I have to initialize maps or something like that) and can I somehow destroy map object? And is destroying the map object even necessary?

$(document).ready(function(){

  // function for showing the map with markers - gmaps4rails gem
  function showMap(){
    var handler = Gmaps.build('Google');
      handler.buildMap({ internal: {id: 'multi_markers'}}, function(){
        var markers = handler.addMarkers([
          { lat: 43, lng: 3.5},
          { lat: 45, lng: 4},
          { lat: 47, lng: 3.5},
          { lat: 49, lng: 4},
          { lat: 51, lng: 3.5}
        ]);
        handler.bounds.extendWith(markers);
        handler.fitMapToBounds();
      });
  }

  // this will hide the element when document is ready
  $("#hidden-element").hide();
  // if I click on button with ID btn-toggle, element will shows up or hide
  $("#btn-toggle").click(function(){
    if ($('#hidden-element').is(':hidden')){
      // is necesarry to have condition and check if element is hidden or visible?
    } else if ($('#hidden-element').is(':visible')){
      // element is hidden? Show it!
      showMap();
    }


    $("#hidden-element").toggle(1000);

  });
});

Solution

  • So it is not an error of library. I think Gmaps4Rails don't know the precise position of the element when element is showing up. So you have to ensure that element is fully visible and then show the map:

    $("#hidden-element").toggle(1000).promise().done(function(){
          if ($('#hidden-element').is(':visible')){
            showMap();
          }
    });
    

    This basically means that maps will load after element is fully visible and took his place on screen.