谷歌地图没有显示

时间:2016-03-20 20:16:14

标签: javascript google-maps google-maps-api-3

我正在尝试将Google地图插入模式中。模态显示出地图的形状,但它全都是灰色的。我搜索并找到了一些建议,例如调用地图的调整大小事件,或者将地图图像的最大宽度设置为无,但这些建议都没有帮助到目前为止。请帮助我。

的javascript

var map;        
            var myCenter=new google.maps.LatLng(53, -1.33);
var marker=new google.maps.Marker({
    position:myCenter
});

function initialize() {
  var mapProp = {
      center:myCenter,
      zoom: 14,
      draggable: false,
      scrollwheel: false,
      mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
  marker.setMap(map);

  google.maps.event.addListener(marker, 'click', function() {

    infowindow.setContent(contentString);
    infowindow.open(map, marker);

  }); 
};
google.maps.event.addDomListener(window, 'load', initialize);

google.maps.event.addDomListener(window, "resize", resizingMap());

$('#myMapModal').on('show.bs.modal', function() {
   //Must wait until the render of the modal appear, thats why we use the resizeMap and NOT resizingMap!! ;-)
   resizeMap();
})

function resizeMap() {
   if(typeof map =="undefined") return;
   setTimeout( function(){resizingMap();} , 400);
}

function resizingMap() {
   if(typeof map =="undefined") return;
   var center = map.getCenter();
   google.maps.event.trigger(map, "resize");
   map.setCenter(center); 
}

HTML

<div class="modal fade" id="myMapModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                 <h4 class="modal-title">Modal title</h4>

            </div>
            <div class="modal-body">
                <div class="container">
                    <div class="row">
                        <div id="map-canvas" class=""></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </div>

CSS

#map-canvas  {
  margin: 0;
  padding: 0;
  height: 100%;
}

#map-canvas {
  width:500px;
  height:480px;
}

1 个答案:

答案 0 :(得分:3)

模型地图div在启动时是不可见的并且没有创建好...我建议你在resizenMap函数的resizeMap中调用初始化函数

function resizeMap() {
  initialize()
  if(typeof map =="undefined") return;
  setTimeout( function(){resizingMap();} , 400);
}

function resizingMap() {
  initialize()
  if(typeof map =="undefined") return;
  var center = map.getCenter();
  google.maps.event.trigger(map, "resize");
  map.setCenter(center); 
}

无论如何,当你打开模态时,你必须“初始化”地图..在创建地图时,包含地图的div必须是可见的..