Javascript – Google Maps API load failure (“‘google’ is undefined”) in IE8

google apigoogle mapsgoogle-maps-api-3internet-explorer-8javascript

When I load http://maps.google.com/maps/api/js?sensor=false in a script tag, everything works fine for me in Chrome, Safari, Firefox, and IE9.

However, when I look in IE9 in compatibility mode (or, I'm told, in IE8) the map does not load and "'google' is undefined" is logged in the console.

Here's the relevant code, with the line that is triggering the error identified with a comment:

<html>
<head>
<title>Test Map</title>
<script type="application/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
</head>
<body>
<div id="map_canvas"></div>
<script type="text/javascript"> 
var lat=37.763154;
var lon=-122.457941;
var initialZoom=17;
var mapTypeId = 'Custom Map';
var mapStyle = [{featureType:"landscape", elementType:"all", stylers:[{hue:"#dae6c3"},{saturation:16},{lightness:-7}]}, 
                {featureType:"road", elementType:"geometry", stylers:[{hue:"#ffffff"},{saturation:-100},{lightness:100}]}];

//**The error is tripped in this next line, again only in IE9 compatibility mode or IE8*     
var styledMap = new google.maps.StyledMapType(mapStyle);

var mapType = new google.maps.ImageMapType({
    tileSize: new google.maps.Size(256,256),
    getTileUrl: function(coord,zoom) {
        return "img/tiles/"+zoom+"/"+coord.x+"/"+coord.y+".png";
    }
});
var map = new google.maps.Map(document.getElementById("map_canvas"), 
        {center:new google.maps.LatLng(lat,lon),
         mapTypeId:google.maps.MapTypeId.ROADMAP,
         zoom:initialZoom,
         mapTypeControl:false});
map.overlayMapTypes.insertAt(0, mapType);

map.mapTypes.set(mapTypeId, styledMap);
map.setMapTypeId(mapTypeId);
</script>
</body>
</html>

So, for some reason, and only in IE9+compatibility-mode and IE8, the script tag specifying http://maps.google.com/maps/api/js?sensor=false isn't loading and/or executing before the subsequent embedded script in the body.

Are others able to replicate? How do I correct this problem?

Best Answer

The problem, apparently, is that IE 8 doesn't grok "application/javascript". I changed it to "text/javascript" in the <script> tag in the <head> section and now my code works. And, of course, if I change it back to "application/javascript", then it stops working.

Related Topic