Map isn’t showing on Google Maps JavaScript API v3 when nested in a div tag

The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.

See this explanation from Mike Williams’ Google Maps API v2 tutorial:

If you try to use style=”width:100%;height:100%” on your map div, you get a map div that has zero height. That’s
because the div tries to be a percentage of the size of the <body>, but by default the <body> has an indeterminate
height.

There are ways to determine the height of the screen and use that number of pixels as the height of the map div,
but a simple alternative is to change the <body> so that its height is 100% of the page. We can do this by
applying style=”height:100%” to both the <body> and the <html>. (We have to do it to both, otherwise the
<body> tries to be 100% of the height of the document, and the default for that is an indeterminate height.)

Add the 100% size to html and body in your css

    html, body, #map-canvas {
        margin: 0;
        padding: 0;
        height: 100%;
        width: 100%;
    }

Add it inline to any divs that don’t have an id:

<body>
  <div style="height:100%; width: 100%;"> 
    <div id="map-canvas"></div>
  </div>
</body>

Leave a Comment