I'm trying to implement Google Maps API in an OOP way.
First, I create the class and then I add some methods.
However, in the Load() method, I get an error in fireBug
"google.load is not a function"
and I also getting this error if I'm trying to execute it in the constructor.
Any ideas? Thanks in advance.
B.R Carl
// Class Map
function Map() {
var self = this;
var script = document.createElement("script");
//script.src = "http://www.google.com/jsapi?key=MyAPIKey=self.Load";
script.src = "http://www.google.com/jsapi?key=MyAPIKey";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
//google.load("maps", "2", {"callback" : self.Loaded}); //This does not work
}
Map.prototype.Load = function() {
//AJAX API is loaded successfully.
google.load("maps", "2", {"callback" : self.Loaded()});
}
Map.prototype.Loaded = function() {
var map = new GMap2(document.getElementById("map_canvas"));
map.setMapType(G_SATELLITE_MAP);
map.setCenter(new GLatLng(11.11, 22.22), 5);
}
map = new Map;
map.Load();
There are several problems in your code. The error you are getting is causes by the first problem:
You are calling google.load()
(inside map.Load()
) before the script containing Google Loader is loaded. You have to use callback to be notified when the script is loaded (see the dynamic loading section in the documentation of Google Loader, notice especially the callback
parameter in script.src
value). You simply can't use google.load()
function before the callback is called.
In google.load
function you are setting the callback wrongly. It seems you want map.Loaded()
function to be called as the callback. But you are doing something different. You are calling map.Loaded()
instantly and passing its return value as the name of the callback function. And since map.Loaded()
isn't returning any value you haven't specified any callback. To fix this remove the brackets - use self.Loaded
instead of self.Loaded()
.
You should not use self
when you specify callback function. Callback function have to be globally visible. When you use self
, you are referencing the global scope. If you have defined a global function named Loaded
it is called instead of map.Loaded()
function. If you haven't defined any global function of that name, you get an error.
To fix the prolems your code should contain something like this (provided that the map
variable is globally visible):
// Class Map
function Map() {
var self = this;
var script = document.createElement("script");
script.src = "http://www.google.com/jsapi?key=MyAPIKey&callback=map.Load";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
Map.prototype.Load = function() {
//AJAX API is loaded successfully.
google.load("maps", "2", {"callback" : map.Loaded});
}
Map.prototype.Loaded = function() {
var map = new GMap2(document.getElementById("map_canvas"));
map.setMapType(G_SATELLITE_MAP);
map.setCenter(new GLatLng(11.11, 22.22), 5);
}
map = new Map();