在script
呈现之后构建这样的Google地图div
标记,然后调用initialize
来初始化地图,因为我已经将代码包装好了匿名立即调用函数表达式...
(function(){
var map,infoWindow;
//lots of stuff...helper functions to initialize
var initialize=function()
{
//init the map and infoWindow and other stuff here
//manipulate the DOM here...
//add controls that draw shapes on the map here...
};
var loadScript=function()
var script=document.createElement('script');
script.type='text/javascript';
//cannot call initialize...
script.src='http://maps.googleapis.com/maps/api/js?v=3.exp&key=API_KEY&sensor=true&'+'libraries=geometry&'+'callback=initialize';
document.body.appendChild(script);
};
$("map-canvas").ready(loadScript);
})();
我收到错误,指出无法找到全局对象initialize
。我宁愿不解包初始化,因为它在许多场合直接与map
和infoWindow
变量进行交互。
我也试过使用以下代码:
var res=(function(){
var map,infoWindow;
//lots of stuff...helper functions to initialize
var initialize=function()
{
//init the map and infoWindow and other stuff here
//manipulate the DOM here...
//add controls that draw shapes on the map here...
};
var loadScript=function()
var script=document.createElement('script');
script.type='text/javascript';
//cannot call initialize...
script.src='http://maps.googleapis.com/maps/api/js?v=3.exp&key=API_KEY&sensor=true&'+'libraries=geometry&'+'callback=initialize';
document.body.appendChild(script);
};
return {init:initialize};
})();
var loadScript=function()
{
var script=document.createElement('script');
script.type='text/javascript';
//cannot call initialize...
script.src='http://maps.googleapis.com/maps/api/js?v=3.exp&key=API_KEY&sensor=true&'+'libraries=geometry&'+'callback='+res.init;
document.body.appendChild(script);//line 509
};
$("map-canvas").ready(loadScript);
现在说:
GET http://maps.googleapis.com/maps/api/js?v=3.exp&key=PART_OF_API_KEY%20and%20display%20on%20map...have%20to%20figure%20this%20one%20out...}
400 (Bad Request) gmaps.js:509
loadScript gmaps.js:509
c jquery-latest.js:3048
p.fireWith jquery-latest.js:3160
x.extend.ready jquery-latest.js:433
q
答案 0 :(得分:2)
关于尝试#1:
在自执行函数中创建的变量范围是函数。因此,当您使用var
- 关键字时,此变量将不会在函数外部显示。
删除var-keyword,初始化将全局可见。
尝试#2无法正常工作,因为res.init
是一个对象,而不是一个字符串。