2014-03-31 18 views
0

我在尝试学习Google地图时遇到了一个奇怪的问题。谷歌地图不会工作,除非它包含div在身体内

一切都很好,因为我遵循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> 

回答