javascript - Google map 在 div 中时不起作用

标签 javascript api google-maps

我正在尝试使用 Google Maps API,而要包含 map 的 div 只有在不在另一个 div 中时才有效。我用两个 map 创建了一个小示例代码,第一个有效,第二个无效。如果我删除这段代码的文档类型,两者都有效。有什么想法吗?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta content='application/xhtml+xml; charset=UTF-8' http-equiv='content-type' />
    <style type='text/css'>
        html { height: 100% }
        body { height: 100%; margin: 0px; padding: 0px }
        #map_canvas { height: 50% }
        #map_canvas2 { height: 50% }
    </style>
    <title>Map</title>
    <script src='http://maps.google.com/maps/api/js?sensor=false' type='text/javascript'></script>
    <script type='text/javascript'>
        function initialize() {
          var latlng = new google.maps.LatLng(20, 20);
          var myOptions = {
          zoom: 8,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        var map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
        }
    </script>
  </head>
  <body onload='initialize()'>
    <div id='map_canvas'></div>
    <div>
      <div id='map_canvas2'></div>
    </div>
  </body>
</html>

这是它在 Firefox 和 Chrome 中的样子:

alt text

alt text


最佳答案

它确实有效,如果您在 firebug 中检查页面,您会看到正在创建 map 。但是因为你没有对外部 div 应用 CSS 定位,Google map 创建的 map div 定位在第一个 map_canvas 下

您需要定位和设置外部 div 的尺寸,尝试为外部 div 指定像素高度和像素宽度...

编辑

代替:

<div id='map_canvas'></div>
<div>
  <div id='map_canvas2'></div>
</div>

尝试:

<!--<div id='map_canvas'></div>-->
<div style="width:900px;height:900px;">
  <div id='map_canvas2'></div>
</div>

您会看到 map 正在运行...

关于javascript - Google map 在 div 中时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3195187/

相关文章:

javascript - 获取 fooTable 的正确数据值(以刻度或 unix 时间戳为单位)

javascript - 为什么 WCF 服务无法在托管服务器上运行?

algorithm - 检索和存储路线图数据

ios - 在我的 iPhone 上查找应用程序的 URL 方案

javascript - 谷歌地图 : when I put an anchor, 市场成为默认

javascript - 当跨度不包含内容时隐藏父级

javascript - 绘制圆圈,然后使用 html canvas 和 javascript 移动它

java - SOAP:如何在 Java 中调用 CountryInfoService WSDL 文件,例如使用 CapitalCity SOAP 操作

iphone - 未记录的 iphone 的 api 经历过

json - Kimono Labs 需要很长时间才能创建 API