views:

28

answers:

2

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.

+2  A: 

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"));
        }
Srinivas Reddy Thatiparthy
@Marcel Korpel ,yeah edited.
Srinivas Reddy Thatiparthy
+1  A: 

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&amp;v=2.x&amp;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>
Marcel Korpel
With your first and last line I get an error about undefined loadMap() error, but when I comment out the first and last line, it works perfectly
astropanic
@astropanic: Yeah, that was because the `documentReady` function was executed after the self-executing anonymous function ended. Now you pollute the global scope a bit more, but it works.
Marcel Korpel
thanks, Perfect!
astropanic