Search code examples
javascriptgoogle-mapsscopeself-invoking-function

How do I pass google maps object into my Self Invoking JS function?


I have simplified the example for this question,but it cannot find the Google maps object. it returns TypeError:a is null.

Any ideas? I presume its a scope issues or something but am completetly stuck

Thanks for any thoughts.

(function ($, document){

    mapOptions = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);

})(jQuery, document);

Solution

  • Keep in mind that your code runs when the page is still being loaded. It's possible that the maps library of google hasn't been loaded yet.

    You have to use a construction like this:

    (function ($, document){
        google.load("maps", function () {
            // here maps is guaranteed to be available
        });
        // here maps may _not_ be available
    })(jQuery, document);