2
votes

I am developing a widget to show some data from my site to others. For that I have to load some script files dynamically via javascript createElement method. Here is my code.

<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.onload = function() {
//initMap();
};
script.src = "http://maps.google.com/maps/api/js?sensor=false";
document.getElementsByTagName('head')[0].appendChild(script);
function initMap()
{
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
 zoom: 12,
 center: myLatlng,
 mapTypeId: google.maps.MapTypeId.ROADMAP

}; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title:"Hello World!"
});
}
$(document).ready(function(){
initMap();
});
</script>

This code initialize map neither in script.onload function and not on document.ready. Thanks in advance.

1

1 Answers

1
votes

I am not sure why, but it seems google maps api is not loaded completely when dynamically loaded. Instead you can use Google Loader https://developers.google.com/loader/ which does fine.

Here is your modified <script>:

var script = document.createElement('script');
script.src = "https://raw.github.com/getify/LABjs/master/LAB.min.js";
script.onload = function() {
    $LAB
        .script('http://code.jquery.com/jquery-1.8.0.min.js')
        // .script('...') // other scripts which DO NOT depend on maps API

        // if script X depends on jquery for example, it must be loaded like this:
        // .wait() // this makes sure scripts above (jquery) are loaded before continuing
        // .script('X')
        .script('https://www.google.com/jsapi')
        .wait(function() {
            // this is called after everything above is loaded
            google.load("maps", "3", 
                {
                    "callback" : onMapsLoad, // called when maps api loaded
                    "other_params": "sensor=false"
                });
        });
};
document.getElementsByTagName('head')[0].appendChild(script);

function onMapsLoad() {
    $LAB
        // add here scripts which DEPEND on Maps API
        .script('https://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js')
        .wait(
            function() {
                // called when all above is loaded
                $(function() { // makes sure DOM is ready
                    initMap();
                });
            }
        );
}

function initMap()
{
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
 zoom: 12,
 center: myLatlng,
 mapTypeId: google.maps.MapTypeId.ROADMAP
}; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title:"Hello World!"
});
}