207
votes

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?

26

26 Answers

318
votes

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

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. ;)

34
votes

You can also get this error if you don't specify center or zoom in your map options.

26
votes

google uses id="map_canvas" and id="map-canvas" in the samples, double-check and re-double-check the id :D

23
votes

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

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
votes

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

6
votes

Also take care not to write

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

correct:

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

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.

5
votes

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

4
votes

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.

3
votes

I had the same issue but the problem was that zoom was not defined within the options object given to Google Maps.

2
votes

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);
}

[...]
1
votes

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() & """...
1
votes

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.

1
votes

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">
1
votes

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
     }
}
1
votes
  • Setup ng-init=init() in your HTML
  • And in the controller

    use $scope.init = function() {...} instead of google.maps.event.addDomListener(window, "load", init){...}

Hope this will help you.

0
votes

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

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)

0
votes

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.

0
votes

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.

0
votes

My fail was to use

zoomLevel

as an option, rather than the correct option

zoom
0
votes

add async defer at the begining of map api key call.

0
votes

In a case I was dealing with, the map div was conditionally rendered depending if the location was being made public. 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:

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

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.