Reputation: 10939
How I can load the Google maps like this:
function loadScript() {
var script = document.createElement("script");
script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAAXN1Nhid00zgr5mrYEM7MhQE7kuAsiuX3WD62vgNgdNYG4wQzhQs7fQD8XzGkuXLIejRfouX3li8xg&async=2&callback=loadMap");
script.setAttribute("type", "text/javascript");
document.documentElement.firstChild.appendChild(script);
}
function loadMap(){
var map = new GMap2(document.getElementById("google_map"));
}
$(document).ready(function(){
loadMap();
//How I can access the map variable here ?
});
And have access to the map variable via jQuery ?
I get an undefined error, because in the time when I try to access the map variable it is not defined yet.
Upvotes: 2
Views: 1076
Reputation: 21763
You can't this way. map
is declared locally to loadMap
and you can't access it outside of that function. Moreover, you have to execute loadScript
first. BTW, don't use setAttribute
to set src
and type
.
Use a variable declared in the outer scope (preferably not the global scope), instead, like
<script>
function loadScript() {
var script = document.createElement("script");
script.src = "http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAAXN1Nhid00zgr5mrYEM7MhQ
script.type = "text/javascript";
document.documentElement.firstChild.appendChild(script);
}
loadScript();
</script>
<!-- close script element here to update DOM -->
<script>
var map; // declared outside loadMap
function loadMap(){
map = new GMap2(document.getElementById("google_map"));
}
$(document).ready(function(){
loadMap();
// Now map is available here
});
</script>
Upvotes: 2
Reputation: 11155
Change the scope of map
variable ,say declare it outside loadMap()
function
modify loadMap()
function to,
var map;
function loadMap(){
loadScript() ;
map = new GMap2(document.getElementById("google_map"));
}
Upvotes: 2