views:

431

answers:

1

Hi, Im trying to load the google maps api's dynamically. I'm using the following code:

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.google.com/jsapi?key=<MY_KEY>;
head.appendChild(script);

but when trying to create the map

map = new GMap2(document.getElementById("map"));

or

map = new google.maps.Map2(document.getElementById("map"));

I'm getting an error that google (or GMap2) is undefined.

+2  A: 

Make sure that you aren't instantiating the map before the Javascript has finished loading.

Also, If you want to use the AJAX API loader, you need to do it like this:

<script src="http://www.google.com/jsapi?key=ABCDEFG" type="text/javascript"></script>
<script type="text/javascript">
    google.load("maps", "2.x");

    // Call this function when the page has been loaded
    function initialize() {
        var map = new google.maps.Map2(document.getElementById("map"));
        map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
    }
    google.setOnLoadCallback(initialize);
</script>

Otherwise, just use the regular Maps API script source:

<script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=abcdefg&amp;sensor=true_or_false" type="text/javascript"></script>
Chris B