简体   繁体   English

Google Maps不会加载jquery

[英]Google Maps doesn't load with jquery

In my Django app I would like to load google map but it doesn't work. 在我的Django应用中,我想加载google map,但是它不起作用。 I have this situation: 我有这种情况:

index.html 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 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. 只需加载mypage.html即可,而不会加载google map。 Can you help me please? 你能帮我吗?

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. 注意:将所有这些代码写入具有div用于map的文件中。

just exclude initialize() function from document.ready 只是排除document.ready中的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);
}

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();
      });
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM