【问题标题】:Google Maps won't work unless its containing div is inside the body除非其包含的 div 位于正文内,否则 Google 地图将无法工作
【发布时间】:2014-03-31 14:53:38
【问题描述】:

我在尝试学习 Google 地图时遇到了一个奇怪的问题。

按照Google Maps 的教程,一切都很好。

但是,当我尝试将地图放置在不是 body div 的 div 中时,事情就出现了问题。例如,而不是

<body>
    <div id="map-canvas"></div>
</body>

我正在尝试这个

<body>
    <div id="mycontainer">
        <div id="map-canvas"></div>
    </div>
</body>

现在它停止工作了! 这没有意义,因为Javascript使用getElementById()函数,所以id的确切位置应该不重要吧?

Live Demo

守则

<!DOCTYPE html>
<html>
  <head>
    <title>Asynchronous Loading</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 99%;
        margin: 60px;
        padding: 0px
      }
    </style>
    <script>
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;

    </script>
  </head>
  <body>
    <div id="myContainer">
        <div id="map-canvas"></div>
    </div>
  </body>
</html>

【问题讨论】:

    标签: javascript html google-maps


    【解决方案1】:

    您需要高度和宽度才能显示地图。 body&lt;div id="mycontainer"&gt;&lt;div id="map-canvas"&gt; 需要使用固定数字而不是百分比设置高度和宽度。 Read similar question

    你的小提琴http://jsfiddle.net/6JR39/1/

    【讨论】:

    • 太好了 - 感谢您的解释。我相信它会在未来的这种情况下有所帮助。
    猜你喜欢
    • 2019-11-09
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多