Javascript – Google MAP API Uncaught TypeError: Cannot read property ‘offsetWidth’ of null

google-maps-api-3javascript

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?

Best Answer

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