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?
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".
add async defer at the begining of map api key call.
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. ;)
I had single quotes in my
and replaced them with double quotes
This did the trick for me.
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
In order to solve it you need to add
async defer
to the script.It should be like this:
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.