Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing a Google Maps error in IE8?

We are using Google Maps and have identified an issue that only seems to happen in IE8 (and possibly below). The functionality works correctly in FF, Chrome, IE9.

The code that the error happens around is:

google.load("maps", "3.x", { other_params: "sensor=false" });
    var mapdiv = null;
    $(function () {
        mapdiv = document.getElementById("map");
        map = new google.maps.Map( mapdiv, {
            zoom: 1,
            center: new google.maps.LatLng(6, 35),
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        });
        var latlngbounds = new google.maps.LatLngBounds( );

In particular on this line:

map = new google.maps.Map( mapdiv, {
    zoom: 1,
    center: new google.maps.LatLng(6, 35),
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.TERRAIN
});

and the error is:

Object doesn't support this property or method

I've had a bit of a play with the IE dev tools and if I replace map = with something like var x = there isnt any error, so this leads me to believe that the map object is the culprit that is missing some property/method. Although I don't really know where the map object comes from, I assume it gets loaded from the google.load call.

Does anyone know what is going on here?

like image 752
Daniel Powell Avatar asked May 23 '12 23:05

Daniel Powell


1 Answers

When the line:

map = new google.maps.Map(mapdiv, { zoom: 1, center: new google.maps.LatLng(6, 35), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.TERRAIN });

gets executed the JavaScript interpreter will start traversing up the scope chain looking for where map is declared. Since it's not declared locally, i.e. var map = ..., it doesn't find it in your local scope, and it ultimately gets added to the global scope.

In your case map is already defined in the global scope as window.map because, it's the Id of a div on your page. In all the browsers you don't see an error message, window.map is set to a new google.maps.Map object. For some reason, good or bad, IE8 won't let you create a global variable whose name conflicts with an existing global variable that refers to a DOM element.

You could resolve this several different ways:

  1. Create a local var map
  2. Change the id of your div from map to something else
  3. If you have to have map exist in global scope, set it using window.map =...

    (3b) Change the variable name to be one that doesn't conflict with window.map, e.g. myMap = new google.maps.Map(...

like image 151
gowansg Avatar answered Oct 08 '22 21:10

gowansg