我试图使用下面的代码使用谷歌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”为空

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

你有什么线索吗?


当前回答

这个问题通常是由于地图div在需要访问它的javascript运行之前没有被渲染。

您应该将初始化代码放在onload函数内或HTML文件的底部,就在标记之前,这样DOM在执行之前就会完全呈现(注意,第二个选项对无效HTML更敏感)。

注意,正如matthewsheets指出的那样,这也可能是由于div的id在你的HTML中根本不存在(div不被渲染的病态情况)

从wf9a5m75的帖子中添加代码样本,将所有内容放在一个地方:

<script type="text/javascript">

function initialize() {
    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);
}
google.maps.event.addDomListener(window, "load", initialize);

</script>

其他回答

为了解决这个问题,你需要在脚本中添加async defer。

应该是这样的:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>

在这里可以看到async defer的含义。

因为你将从主js文件中调用一个函数,你还想确保它在你加载主脚本的那个文件之后。

如果你碰巧使用asp.net Webforms,并且正在使用母版页在页面后面的代码中注册脚本,不要忘记使用map元素(vb.net)的clientID:

ClientScript.RegisterStartupScript(Me.[GetType](), "Google Maps Initialization", String.Format("init_map(""" & map_canvas.ClientID() & """...

检查你没有重写window.self

我的问题:我创建了一个组件,并写了self = this而不是var self = this。如果你不使用关键字var, JS会把这个变量放在window对象上,所以我覆盖了window。导致此错误的Self。

谷歌在样例中使用id="map_canvas"和id="map-canvas",反复检查id:D

在我的案例中,这些问题都是使用defer https://developer.mozilla.org/en/docs/Web/HTML/Element/script解决的

<脚本src=“<你的文件>.js”

不过,您需要考虑浏览器对该选项的支持(我还没有看到问题)