Loading Google Maps API with Ajax using Javascript/JQuery, Callback not setup correctly

10,775

Figured out a solution, essentially my callback wasn't necessary. Here's what I used:

$('.button').click(function() {
        $('#mapcontainer').load('/map.html', function () {
       initialize();
   });
}); 

and

<script>
function initialize(){
   var mapOptions = {
           ///Map options go here
     }
   };

   map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
</script>

<div style="height:400px;width:650px;" id="map_canvas"></div>
Share:
10,775
GSimon
Author by

GSimon

Updated on June 05, 2022

Comments

  • GSimon
    GSimon almost 2 years

    I would appreciate some guidance on getting this script to work. The map loads fine but the Callback isn't setup correctly so the page keeps appending the Google maps API script to the document each time the button is clicked.

    I am using JQuery's $.load to add an HTML page (map.html) into a DOM element (a div container).

    $('.button').click(function() {
            $('#mapcontainer').load('/map.html');
    }); 
    

    Here is what map.html is using to load the map, the script I'm using originated from here: https://stackoverflow.com/a/12602845/1607449

    <script>
    
    var gMapsLoaded = false;
    window.gMapsCallback = function(){
    gMapsLoaded = true;
    $(window).trigger('gMapsLoaded');}
    
    window.loadGoogleMaps = function(){
    if(gMapsLoaded) return window.gMapsCallback();
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src","http://maps.google.com/maps/api/js?key=KEYGOESHERE&sensor=false&callback=gMapsCallback");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    }
    
    $(document).ready(function(){
    
       function initialize(){
    
    var mapOptions = {
    
      }
    };
    
    map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
    }
    
    $(window).bind('gMapsLoaded', initialize);
    window.loadGoogleMaps();
    });
    
    </script>
    
    <div style="height:400px;width:650px;" id="map_canvas"></div>
    

    Here's another example of a different way to setup a callback for dynamically loading the Google Maps Javascript API: http://www.vijayjoshi.org/2010/01/19/how-to-dynamically-load-the-google-maps-javascript-api-on-demand-loading/ This is what I am hoping to accomplish by modifying the script I'm currently using (as opposed to back-engineering a new script).

    Thanks.

    Edit: Solved the issue, solution posted in response below

  • lharby
    lharby over 9 years
    Just voted on this as it solved a problem I was having. Much appreciated.