If you've been around the Google AJAX APIs for long, you've probably
realized by now that there are at least two different naming schemes
out there for the various classes and variables that you use on a
daily basis: G* and google.*.*. Usually, this isn't a huge deal
because you have direct control over how the API(s) is loaded onto the
page, but what if you don't have that control.
For instance, I was recently working on a couple of projects that were
intended to be made available for the public to use. As I was writing
the code, I suddenly realized that I wouldn't know for sure which
naming scheme I needed to us, and with the recent addition of the
nooldnames option to the API loader and the fact that Maps doesn't
load the google.maps.* namespace unless called via the loader,
programming for either one or the other would not be an option.
So I came up with a little function that takes two arguments and hunts
through the DOM to find the Google class or property you're looking
for:
function findInGoogleNamespace(a,b){
b=b.replace(/^G\_?(?![a-z])/,'');
b=b.replace(/^G((web|local|image|news|video|blog|book|adSense|
sa))/,function(d,e){return e.replace(/^./,function(f){return
f.toUpperCase();});});
var bA=b.replace(/^([A-Z])/,function(d){return d.toLowerCase();});
if(typeof(google)!='undefined'&&typeof(google[a])!
='undefined'&&typeof(google[a][b])!='undefined'){
return google[a][b];
}else if(window['G'+b]){
return window['G'+b];
}else if(window['G'+bA]){
return window['G'+bA];
}else if(window['G_'+b]){
return window['G_'+b];
}else{
throw('jGMLSC error: Unable to locate '+b+' in Google '+a+'
namespace.');
}
}
Here's how it works:
1. You call
findInGoogleNamespace('which_api','what_you're_looking_for');
2. The function will check to see if the class exists in the
google.API.* namespace
3. The function will check to see if the class exists in the G*
namespace
In fact, it'll even find the non-standardized references included in
the Maps API (e.g., G_NORMAL_MAP).
Here are a couple of example usages:
var myMap=new (findInGoogleNamespace('maps','Map2'))();
var myWebSearch=new (findInGoogleNamespace('search','WebSearch'))();
var myFeedControl=new (findInGoogleNamespace('feeds','GFeedControl'))
();
In fact, if you were paying attention to that last line, you'll notice
that findInGoogleNamespace will find the class or property you're
looking for, regardless of whether or not you provide it's description
with a leading G.
And it's posted here for you to use, free of charge. All I ask is
that you maybe drop me a line to you're using it and how! Happy
coding!
Jeremy R. Geerdes
Effective website design & development
Des Moines, IA
For more information or a project quote:
http://jgeerdes.home.mchsi.com
jgee...@mchsi.com
If you're in the Des Moines, IA, area, check out Debra Heights
Wesleyan Church!