Google地图未显示(未加载)

时间:2017-02-18 02:15:43

标签: javascript jquery api google-maps

我没有谷歌地图API的经验,所以我希望你能帮助我。

问题是每当我点击显示按钮时,地图的宽度就会出现,但是没有加载,我根本看不到地图。

但是如果我在开发者工具中打开建议,地图就会正常加载!

codepen url以获得更好的解释 https://codepen.io/ahmadz12/pen/QdRQbE

HTML

<div id="map-canvas" class='hide'></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" type="text/javascript"></script>
<a id='show'>show</a>

CSS

#map-canvas{
  height: 500px;
  width: 500px;
  border: 3px solid black;
}
.hide{
  display:none;
}

的javascript

if (document.getElementById('map-canvas')){

    // Coordinates to center the map
    var myLatlng = new google.maps.LatLng(52.525595,13.393085);

    // Other options for the map, pretty much selfexplanatory
    var mapOptions = {
        zoom: 14,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // Attach a map to the DOM Element, with the defined settings
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

}
$('#show').click(function(){
 $('#map-canvas').removeClass( "hide" )
});

由于

1 个答案:

答案 0 :(得分:3)

当您将Google地图加载到隐藏的div中然后显示该div时,您需要告诉Google重绘地图:

$('#show').click(function(){
    $('#map-canvas').removeClass( "hide" );
    google.maps.event.trigger(map, 'resize');
});

我怀疑Google正试图通过保存浏览器资源来提供帮助,而不是在无法看到的元素中绘制地图。通过在显示div时触发调整大小,可以让Google在现在可见的元素中再次绘制地图。

相关问题