可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I\'m trying to use Google MAP API v3 with the following code.
<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
I have no idea, since I follow the direction given in this tutorial.
Do you have any clue?
回答1:
This problem is usually due to the map div not being rendered before the javascript runs that needs to access it.
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).
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)
Adding code sample from wf9a5m75\'s post to put everything in one place:
<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>
回答2:
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.
In other words, make sure your IDs match up. ;)
回答3:
google uses id=\"map_canvas\"
and id=\"map-canvas\"
in the samples, double-check and re-double-check the id :D
回答4:
Year, geocodezip\'s answer is correct.
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>
回答5:
You can also get this error if you don\'t specify center
or zoom
in your map options.
回答6:
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:
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
. Once I\'ve set the size of this div in CSS like this
#map {
width: 500px;
height: 300px;
}
everything worked! Hope this helps someone.
回答7:
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. as soon as i changed it to two open&close tags <div id=\"map1\"></div>
it worked. hth
回答8:
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.
回答9:
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. It\'s not the dash; it doesn\'t seem to work with any other ID than \"map\".
回答10:
Also take care not to write
google.maps.event.addDomListener(window, \"load\", init())
correct:
google.maps.event.addDomListener(window, \"load\", init)
回答11:
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. Just a quick reminder for someone in a hurry.
回答12:
I had the same issue but the problem was that zoom was not defined within the options object given to Google Maps.
回答13:
If you\'re creating multiple maps in a loop, if a single map DOM element doesn\'t exist, it breaks all of them. First, check to make sure the DOM element exists before creating a new Map object.
[...]
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);
}
[...]
回答14:
If you happen to be using asp.net Webforms and are registering the script in the code behind of a page using a master page, don\'t forget to use the clientID of the map element (vb.net):
ClientScript.RegisterStartupScript(Me.[GetType](), \"Google Maps Initialization\", String.Format(\"init_map(\"\"\" & map_canvas.ClientID() & \"\"\"...
回答15:
In order to solve it you need to add async defer
to the script.
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.
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.
回答16:
Make sure you include the Places library &libraries=places
parameter when you first load the API.
For example:
<script src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places\">
回答17:
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. You can also check if the div exists first before loading the google maps function call. 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
}
}
回答18:
回答19:
Actually easiest way to fix this is just move your object before Javascript code it worked to me. I guess in your answer object is loaded after javascript code.
<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>
回答20:
In my case these sort of issues were solved using 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)
回答21:
Check that you\'re not overriding window.self
My issue: I had created a component and wrote self = this
instead of 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.
回答22:
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.
original edited post
Also got this error while using ReactJS while following this blog post. sahat\'s comment here helped -
see the content of sahat\'s comment below.
❗️ Note for React >= 0.9
Prior to v0.9, the DOM node was passed in as the last argument. If you were using this, you can still access the DOM node by calling this.getDOMNode().
In other words, replace rootNode parameter with this.getDOMNode() in the latest version of React.
回答23:
My fail was to use
zoomLevel
as an option, rather than the correct option
zoom
回答24:
add async defer at the begining of map api key call.
回答25:
Here the problem was the API link without the key
param:
<script type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?libraries=places&key=YOURKEY\"></script>
That way works fine.