Google Maps: asynchronous loading with coffeescript

I’m trying to emulate this asynchronously-loaded map using coffeescript.

This is my coffeescript:

  • nodejs async nested calls
  • Race condition in JavaScript with compound assignment
  • Handling multiple call asynchronous callbacks
  • Async update of array in Angular
  • Extract inner from a span element in selenium/protractor javascript
  • angularjs: how to do fire-and-forget with $http
  • initialize = ->
      mapOptions =
        zoom: 8
        center: new google.maps.LatLng(-34.397, 150.644)
    
      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions)
      return
    
    loadScript = ->
      script = document.createElement("script")
      script.type = "text/javascript"
      script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&" + "callback=initialize"
      document.body.appendChild script
      return
    
    
    $(window).load ->
    
    loadScript() 
    

    Which compiles to:

    (function() {
    var initialize, loadScript;
    
    initialize = function() {
      var map, mapOptions;
      mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(-34.397, 150.644)
      };
      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    };
    
    loadScript = function() {
      var script;
      script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&" + "callback=initialize";
      document.body.appendChild(script);
    };
    
    $(window).load(function() {
      return loadScript();
    });
    
    }).call(this);
    

    Then I get the error:

    Uncaught TypeError: Object [object global] has no method 'initialize'

    I understand that I probably need to make the initialize() method accessible to the document’s scope, but since coffeescript wraps all modules in anonymous functions what’s the best way of making this work?

  • Call async/await functions in parallel
  • Asynchronous Javascript with Promises and unit/integration tests
  • How to pass data around from an asynchronous function in NodeJS, using unconventional methods?
  • Node.Js VS HttpAsync (asp.net)
  • Javascript blocking until image preload complete?
  • Way to asynchronously load Google Translate widget for your website?
  • One Solution collect form web for “Google Maps: asynchronous loading with coffeescript”

    window.initialize = ->
      # ...
    

    P.S. Consider giving it a more unique name.