我试图使用下面的代码使用谷歌MAP API v3。

<h2>Topology</h2>

<script src="https://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

<link rel="stylesheet" type="text/css" href="{% url css_media 'tooltip.topology.css' %}" />
<link rel="stylesheet" type="text/css" href="{% url css_media 'tooltip.css' %}" />

<style type="text/css" >
      #map_canvas {
              width:300px;
            height:300px;
     }
</style>

<script type="text/javascript">

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);

</script>

<div id="map_canvas"> </div>

当我运行这段代码时,浏览器会这样说。

无法读取属性“offsetWidth”为空

我不知道,因为我遵循本教程中给出的方向。

你有什么线索吗?


当前回答

我的失败是没有使用

zoomLevel

作为一种选择,而不是正确的选择

zoom

其他回答

在我处理的一个案例中,地图div是有条件地呈现的,这取决于位置是否被公开。如果你不能确定是否地图画布div将在页面上,只需检查你的文档。getElementById返回一个元素,只在它存在时调用映射:

var mapEle = document.getElementById("map_canvas");
if (mapEle) {
    map = new google.maps.Map(mapEle, myOptions);
}

实际上最简单的方法来解决这个问题,只是移动你的对象之前Javascript代码,它对我有用。我猜在你的答案对象是加载后javascript代码。

<style type="text/css" >
      #map_canvas {
              width:300px;
            height:300px;
     }

 <div id="map_canvas"> </div> // Here 

<script type="text/javascript">

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);

</script>

<div id="map_canvas"> </div>

如果在循环中创建多个映射,如果单个映射DOM元素不存在,则会破坏所有映射。首先,在创建新的Map对象之前,检查以确保DOM元素存在。

[...]

for( var i = 0; i <= self.multiple_maps; i++ ) {

  var map_element = document.getElementById( 'map' + '-' + i.toString() );

  // Element doesn't exist, don't create map!
  if( null === map_element ) {
    continue;
  }

  var map = new google.maps.Map( map_element, myOptions);
}

[...]

确保在第一次加载API时包含了Places库&libraries= Places参数。

例如:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

改变ID(在所有3个地方)从“map-canvas”到“map”为我修复了它,即使我已经确保ID是相同的,div有宽度和高度,代码直到窗口加载调用后才运行。不是破折号;除了“map”,它似乎不能与任何其他ID一起工作。