简体   繁体   English

Google MAP API未捕获TypeError:无法读取null的属性'offsetWidth'

[英]Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

I'm trying to use Google MAP API v3 with the following code. 我正在尝试使用以下代码使用Google 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>

When I run this code, the browser says this. 当我运行此代码时,浏览器会这样说。

Uncaught TypeError: Cannot read property 'offsetWidth' of null 未捕获的TypeError:无法读取null的属性'offsetWidth'

I have no idea, since I follow the direction given in this tutorial . 我不知道,因为我遵循本教程中给出的指示。

Do you have any clue? 你有什么线索吗?

This problem is usually due to the map div not being rendered before the javascript runs that needs to access it. 此问题通常是由于在运行需要访问它的javascript之前未映射map div。

You should put your initialization code inside an onload function or at the bottom of your HTML file, just before the tag, so the DOM is completely rendered before it executes (note that the second option is more sensitive to invalid HTML). 您应该将初始化代码放在onload函数内或HTML文件的底部,就在标记之前,因此DOM在执行之前完全呈现(请注意,第二个选项对无效HTML更敏感)。

Note, as pointed out by matthewsheets this also could be cause by the div with that id not existing at all in your HTML (the pathological case of the div not being rendered) 请注意,正如matthewsheets所指出的那样,这也可能是因为你的HTML中根本不存在id的div(div的病理情况没有被渲染)

Adding code sample from wf9a5m75 's post to put everything in one place: 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>

For others that might still be having this issue , even after trying the above recommendations, using an incorrect selector for your map canvas in the initialize function can cause this same issue as the function is trying to access something that doesn't exist. 对于可能仍然存在此问题的其他人 ,即使在尝试上述建议之后,在初始化函数中使用错误的选择器作为地图画布也会导致同样的问题,因为该函数试图访问不存在的内容。 Double-check that your map Id matches in your initialize function and your HTML or this same error may be thrown. 仔细检查您的地图ID是否与您的初始化函数匹配,并且您的HTML或同样的错误可能会被抛出。

In other words, make sure your IDs match up. 换句话说,请确保您的ID匹配。 ;) ;)

谷歌在样本中使用id="map_canvas"id="map-canvas" ,仔细检查并重新检查id:D

如果未指定centerzoom地图选项,也可能会出现此错误。

Year, geocodezip's answer is correct. 一年,geocodezip的答案是正确的。 So change your code like this: (if you still in trouble, or maybe somebody else in the future) 所以改变你的代码:(如果你仍然遇到麻烦,或者将来可能还有其他人)

<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>

Just so I add my fail scenario in getting this to work. 就这样,我添加了失败的场景,让它发挥作用。 I had a <div id="map> in which I was loading the map with: 我有一个<div id="map> ,我在其中加载地图:

var map = new google.maps.Map(document.getElementById("map"), myOptions);

and the div was initially hidden and it didn't have explicitly width and height values set so it's size was width x 0 . 并且div最初是隐藏的,并且它没有明确设置宽度和高度值,所以它的大小是width x 0 Once I've set the size of this div in CSS like this 一旦我像这样在CSS中设置这个div的大小

#map {
    width: 500px;
    height: 300px;
}

everything worked! 一切正常! Hope this helps someone. 希望这有助于某人。

For even more others that might still be having this issue, I was using a self-closing <div id="map1" /> tag, and the second div was not showing, and did not seem to be in the dom. 对于可能仍然存在这个问题的更多其他人,我使用了一个自动关闭的<div id="map1" />标签,而第二个div没有显示,并且似乎没有在dom中。 as soon as i changed it to two open&close tags <div id="map1"></div> it worked. 一旦我将其更改为两个打开和关闭标签<div id="map1"></div>就可以了。 hth 心连心

I had single quotes in my 我的单引号

var map = new google.maps.Map( document.getElementById('map_canvas') );

and replaced them with double quotes 并用双引号替换它们

var map = new google.maps.Map( document.getElementById("map_canvas") );

This did the trick for me. 这对我有用。

Also take care not to write 还要注意不要写

google.maps.event.addDomListener(window, "load", init())

correct: 正确:

google.maps.event.addDomListener(window, "load", init)

Changing the ID (in all 3 places) from "map-canvas" to "map" fixed it for me, even though I had made sure the IDs were the same, the div had a width and height, and the code wasn't running until after the window load call. 将ID(在所有3个地方)从“map-canvas”更改为“map”为我修复了它,即使我确定ID相同,div也有宽度和高度,代码不是运行到窗口加载调用之后。 It's not the dash; 这不是破折号; it doesn't seem to work with any other ID than "map". 它似乎不适用于任何其他ID而不是“地图”。

Also, make sure you're not placing hash symbol (#) inside your selector in a 另外,请确保您没有在选择器中放置哈希符号(#)

    document.getElementById('#map') // bad

    document.getElementById('map') // good

statement. 声明。 It's not a jQuery. 这不是一个jQuery。 Just a quick reminder for someone in a hurry. 快速提醒一下匆忙的人。

我遇到了同样的问题,但问题是缩放没有在给予谷歌地图的选项对象中定义。

If you're creating multiple maps in a loop, if a single map DOM element doesn't exist, it breaks all of them. 如果您在循环中创建多个映射,如果不存在单个映射DOM元素,则会中断所有映射。 First, check to make sure the DOM element exists before creating a new Map object. 首先,在创建新的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);
}

[...]

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

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

In order to solve it you need to add async defer to the script. 为了解决这个问题,您需要在脚本中添加async defer

It should be like this: 它应该是这样的:

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

See here the meaning of async defer. 在这里看到async defer的含义。

Since you'll be calling a function from the main js file, you also want to make sure that this is after the one where you load the main script. 由于您将从主js文件调用函数,因此您还需要确保它位于加载主脚本的函数之后。

  • Setup ng-init=init() in your HTML 在HTML中设置ng-init = init()
  • And in the controller 并在控制器中

    use $scope.init = function() {...} instead of google.maps.event.addDomListener(window, "load", init){...} 使用$ scope.init = function(){...}而不是google.maps.event.addDomListener(window,“load”,init){...}

Hope this will help you. 希望这会帮助你。

Make sure you include the Places library &libraries=places parameter when you first load the API. 首次加载API时,请确保包含Places库&libraries=places参数。

For example: 例如:

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

I know I'm a bit late to the party, just wanted to add that the error can also happen when the div doesn't exist in the page. 我知道我有点迟到了,只是想补充一点,当页面中不存在div时也会发生错误。 You can also check if the div exists first before loading the google maps function call. 您还可以在加载Google地图函数调用之前先检查div是否存在。 Something like 就像是

function initMap() {
    if($("#venuemap").length != 0) {
        var city= {lat: -26.2041, lng: 28.0473};
        var map = new google.maps.Map(document.getElementById('venuemap'), {
       etc etc
     }
}

Actually easiest way to fix this is just move your object before Javascript code it worked to me. 实际上解决这个问题最简单的方法就是在我的Javascript代码之前移动你的对象。 I guess in your answer object is loaded after javascript code. 我猜你的答案对象是在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>

In my case these sort of issues were solved using defer https://developer.mozilla.org/en/docs/Web/HTML/Element/script 在我的情况下,使用defer https://developer.mozilla.org/en/docs/Web/HTML/Element/script解决了这些问题。

<script src="<your file>.js" defer></script>

You need to take into account browsers's support of this option though (I haven't seen problems) 您需要考虑浏览器对此选项的支持(我没有看到问题)

Check that you're not overriding window.self 检查你是不是覆盖了window.self

My issue: I had created a component and wrote self = this instead of var self = this . 我的问题:我创建了一个组件并编写了self = this而不是var self = this If you don't use the keyword var , JS will put that variable on the window object, so I overwrote window.self which caused this error. 如果你不使用关键字var ,JS会把那个变量放在window对象上,所以我覆盖了window.self ,导致了这个错误。

This is an edit of a previously deleted post to contain the content of the linked answer, in the answer itself. 这是对以前删除的帖子的编辑,以包含答案本身中链接答案的内容。 The purpose for re-publishing this answer is to function as a PSA for React 0.9+ users who have also stumbled into this issue. 重新发布此答案的目的是作为React 0.9+用户的PSA,他们也偶然发现了这个问题。

original edited post 原编辑的帖子


Also got this error while using ReactJS while following this blog post . 在关注此博客文章时使用ReactJS时也出现此错误。 sahat's comment here helped - see the content of sahat's comment below. sahat的评论在这里有所帮助 - 请参阅下面sahat评论的内容。

❗️ Note for React >= 0.9 ❗️React> = 0.9

Prior to v0.9, the DOM node was passed in as the last argument. 在v0.9之前,DOM节点作为最后一个参数传入。 If you were using this, you can still access the DOM node by calling this.getDOMNode(). 如果您使用它,您仍然可以通过调用this.getDOMNode()来访问DOM节点。

In other words, replace rootNode parameter with this.getDOMNode() in the latest version of React. 换句话说,在最新版本的React中使用this.getDOMNode()替换rootNode参数。

My fail was to use 我的失败是使用

zoomLevel

as an option, rather than the correct option 作为一种选择,而不是正确的选择

zoom

在map api key call的开头添加async defer。

In a case I was dealing with, the map div was conditionally rendered depending if the location was being made public. 在我正在处理的情况下,地图div有条件地呈现,具体取决于该位置是否被公开。 If you can't be sure whether the map canvas div will be on the page, simply check that your document.getElementById is returning an element and only invoke the map if it's present: 如果您无法确定地图canvas div是否在页面上,只需检查您的document.getElementById是否正在返回一个元素,并且只有在它出现时才调用该地图:

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

Here the problem was the API link without the key param: 这里的问题是没有key参数的API链接:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places&key=YOURKEY"></script>

That way works fine. 这样做很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google Map API,未捕获的TypeError:无法读取null的属性“ offsetWidth” - Google map API, Uncaught TypeError: Cannot read property 'offsetWidth' of null google maps api v3未捕获typeError:无法读取null的属性“ offsetWidth” - google maps api v3 uncaught typeError: Cannot read property 'offsetWidth' of null Google Map API BackBoneJS无法读取null的属性&#39;offsetWidth&#39; - Google Map API BackBoneJS Cannot read property 'offsetWidth' of null Enyo JS Uncaught TypeError:无法读取null的属性&#39;offsetWidth&#39; - Enyo JS Uncaught TypeError: Cannot read property 'offsetWidth' of null 错误:未被捕获的TypeError:无法在angularjs中读取Google地图的null属性&#39;offsetWidth&#39; - Error: Uncaught TypeError: Cannot read property 'offsetWidth' of null in angularjs for google maps Google Maps Javascript V3未捕获的TypeError:无法读取null的属性“ offsetWidth” - Google Maps Javascript V3 Uncaught TypeError: Cannot read property 'offsetWidth' of null 未捕获到的TypeError:无法读取Google Map API中未定义的属性“ PlacesService” - Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api 未捕获的类型错误:无法读取 null 的属性“map” - Uncaught TypeError: Cannot read property 'map' of null 未捕获到的TypeError:无法在Google Analytics(分析)API中读取null的属性“ sub” - Uncaught TypeError: Cannot read property 'sub' of null in Google Analytics API 未捕获的类型错误:无法读取未定义的属性“offsetWidth” - chart.js - Uncaught TypeError: Cannot read property 'offsetWidth' of undefined - chart.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM