Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - 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?(你有什么线索吗?)   ask by jaeyong translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...