如何在隐藏元素中启动 Gmap

How to initiate Gmaps in hidden element

本文关键字:启动 Gmap 元素 隐藏      更新时间:2023-09-26

我有一个元素(#hidden-element),默认情况下是隐藏的。当我单击按钮(#btn 切换)时,我想使此元素可见。目前,一切都很好。该元素确实会显示,但是如果我第一次单击该按钮,地图将不会显示。然后我单击以隐藏元素,然后再次单击以第二次显示隐藏元素,现在地图在这里。

所以,我的问题是,我怎么能知道地图将第一次出现(我必须初始化地图或类似的东西),我可以以某种方式破坏地图对象吗?甚至有必要销毁地图对象吗?

$(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);
  });
});

所以这不是库的错误。我认为Gmaps4Rails不知道元素出现时的精确位置。因此,您必须确保该元素完全可见,然后显示地图:

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

这基本上意味着地图将在元素完全可见并在屏幕上占据他的位置后加载。