简体   繁体   中英

Google Maps: asynchronous loading with coffeescript

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

This is my coffeescript:

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?

window.initialize = ->
  # ...

PS Consider giving it a more unique name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM