Basically the callback must be a function that is accessible when you're in global scope(that's where google runs the callback).
The API uses eval
to execute the callback, so the procedure is like this:
//the global callback
function bar(){ alert('callback executed');}
//string provided as callback
callbackname='bar' ;
//execute it
eval('window.'+callbackname+'()') ;
when you take a look at the eval-part it should be possible to run functions that are not defined global, e.g. as properties of objects:
//a global object with a method
foo={bar:function(){ alert('callback executed too');}};
//string provided as callback
othercallbackname='foo.bar';
//execute it
eval('window.'+othercallbackname+'()');
...and it works(also with the maps-API).
The problem: you still need a global thing(foo
in this case).
But it's not a real problem, when you work with google-API's there will be at least 1 global object you can't get rid of: google
So: define the callback as property of the global google
-object.
You may ask how you can set the property of google when you didn't load the API yet : define it on your own before you load the API:
window.google={bar:function(){/*do something*/}};
..then load the API using: callback=google.bar
sample-implementation(suitable for multiple calls):
//create maps of elements with className map
document.addEventListener('click',function(e){
var node=e.target,callback,script,execCallbacks;
//check the class
if(node.className==='map'){
//assign a new class to prevent from further clicks
node.className='mapped';
//when window.google isn't available, create it
if(!window.google){
window.google={};
}
//we will store the callbacks in an array
if(!window.google.callbacks){
window.google.callbacks=[];
}
//function that executes the callbacks
if(!window.google.execCallbacks){
window.google.execCallbacks=function(){
while(this.callbacks.length){
this.callbacks.shift()();
}
};
}
//define the callback(creates a simple map)
callback=function(){
new google.maps.Map(node,
{zoom:1,
center:new google.maps.LatLng(0,0)
});
};
//google.maps isn't loaded yet
if(!window.google.maps){
//push the callback to the callbacks
window.google.callbacks.push(callback);
//load the API
script=document.createElement('script');
script.src="https://maps.googleapis.com/maps/api/js?v=3&" +
"callback=google.execCallbacks";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
}
//API is already loaded, run the callback directly
else{
callback();
}
}
});
Demo: http://jsfiddle.net/doktormolle/gH8FR/