views:

308

answers:

2

Hello,

The follow tells me that GMap2 is not defined. But the code that uses GMap2 is in the callback.

        $(function() {
        $('#sample').click(function() {
            $.getScript("http://maps.google.com/maps?file=api&v=2&sensor=true&key=API_KEY_HERE", function() {
                var map = new GMap2(document.getElementById("mapTest"));
                map.setCenter(new GLatLng(18, -77.4), 13);
                map.setUIToDefault();

            });
        });
    });

<a id="sample">Click Me</a>
<div id="mapTest" style="width: 200px; height: 100px;"></div>
A: 

Did you check the if the browser is compatible? I do this in all my GMAP applications, although it rarely fails...

if (GBrowserIsCompatible()) 
Sparky
It does not find the script any at all. It also tells me that function is not available.
Shawn Mclean
Based on both functions giving errors, it sounded like a script not being load error, but it looks like Doug helped you out. Good luck with your application...
Sparky
+2  A: 

You can go two ways with this:

1. Continue to use $.getScript:

It seems that you need both an async=2 parameter as well as a different callback structure for it to work. My answer is adapted to your code from this great walkthrough here.

<script type="text/javascript">
    function map_callback(){
        var map = new GMap2(document.getElementById("mapTest"));
        map.setCenter(new GLatLng(18, -77.4), 13);
        map.setUIToDefault();
    }

    $(function(){
       $('#sample').click(function(){
          $.getScript("http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=true&amp;amp;callback=map_callback&amp;amp;async=2&amp;amp;key=API_KEY_HERE");
       }
    }
</script>

2. Use the Google AJAX Loader

Since you are already using a Google Library, why not use their loader to help you out:

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"&gt;&lt;/script&gt;
<script type="text/javascript">
   google.load("jquery", "1.3.2");

   google.setOnLoadCallback(function(){
       $('#sample').click(function(){
          google.load("maps", "2", {"callback" : function(){
            var map = new GMap2(document.getElementById("mapTest"));
            map.setCenter(new GLatLng(18, -77.4), 13);
            map.setUIToDefault();
          } });
       }
   }, true); // Passing true, though undocumented, is supposed to work like jQuery DOM ready
</script>
Doug Neiner
Thanks, I tried both and decided to stick with the jquery because the google ajax loader is an extra 16kb.
Shawn Mclean
@Shawn glad it worked for you! Just so you know, it is 16kb uncompressed, but it is sent compressed from the Google servers, so it is only 5.8k
Doug Neiner