RoverDar
RoverDar

Reputation: 441

Google Maps doesn't load with jquery

In my Django app I would like to load google map but it doesn't work. I have this situation:

index.html

    <!DOCTYPE html> 
    <html>
     <head>
        # here other css
        <style>
          #mapCanvas {height: 400px;width: 100%;}    
          .dynamicCanvas {height: 400px;width: 100%;}
        </style>
     </head>
     <body>
       <div id="loadpage"></div>     
       <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MYKEY"></script>

       # here other plugin 

       <script>
         jQuery(document).ready(function($) {

             // click on #btn_map and open the page with the map 
             $( document ).on( "click", '#btn_map', function( e ) {
               e.preventDefault();
               var href = $(this).attr('data-href');                                                                
               $('#loadpage').load("./mypage.html"));          

               // google map initialize  
               function initialize() {
                    var latlng = new google.maps.LatLng(-34.397, 150.644);
                    var myOptions = {
                        zoom: 8,
                        center: latlng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                        };
                   var map = new google.maps.Map(document.getElementById("mapCanvas"),
                myOptions);
                   }
           google.maps.event.addDomListener(window, "load", initialize);  
           });       

         });   

       </script>
  </body>
</html>

mypage.html

<div>
   <div id="mapCanvas" class="dynamicCanvas"></div>
</div>

In the console I don't get errors. Simply the mypage.html load and the google map doesn't load. Can you help me please?

Upvotes: 0

Views: 1193

Answers (1)

Ankush Jain
Ankush Jain

Reputation: 7059

It won't work. You can not bind window load function in a button click for a window which has been already loaded.

  • Note: Write all this code in that file which has div for map.

just exclude initialize() function from document.ready

function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("mapCanvas"),
        myOptions);
}

and call it from button click

 jQuery(document).ready(function($) {

      // click on #btn_map and open the page with the map 
      $(document).on("click", '#btn_map', function(e) {
          initialize();
      });
  });

Upvotes: 1

Related Questions