2016-11-29 71 views
1

我正在嘗試將Google地圖集成到我的web應用程序中,但我的代碼給出了錯誤「google not defined」。集成Google Maps API時出現「google未定義」

有人可以幫我弄明白嗎?提前致謝。

</head><script src="http://maps.google.com/maps/api/js?key=AIzaSyAdXcTNKKaje1AtGQq32SwOMJ5Um-EE5GU " async="" defer="defer" type="text/javascript"></script> 

<body> <div id="map" style="width: 400px; height: 300px;"></div><script type="text/javascript"> 
    function LoadGoogle() 
    { if(typeof google != 'undefined' && google && google.load) 
     { 
      var address = 'UK'; 

      var map = new google.maps.Map(document.getElementById('map'), { 
       mapTypeId: google.maps.MapTypeId.TERRAIN, 
       zoom: 6 
      }); 

      var geocoder = new google.maps.Geocoder(); 

      geocoder.geocode({ 
       'address': address 
      }, 
      function(results, status) { 
       if(status == google.maps.GeocoderStatus.OK) { 
        new google.maps.Marker({ 
         position: results[0].geometry.location, 
         map: map 
        }); 
        map.setCenter(results[0].geometry.location); 
       } 
      }); 
      } 
     else 
     { 
      setTimeout(LoadGoogle, 30); 
     } 
    } 
    LoadGoogle(); </script></body> 

想這也仍然得到同樣的錯誤。

var map = new google.maps.Map(document.getElementById('map'), { 
      mapTypeId: google.maps.MapTypeId.TERRAIN, 
      zoom: 6 
     }); 

     var geocoder = new google.maps.Geocoder(); 

     geocoder.geocode({ 
      'address': address 
     }, 
     function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       new google.maps.Marker({ 
        position: results[0].geometry.location, 
        map: map 
       }); 
       map.setCenter(results[0].geometry.location); 
      } 
     }); 
+0

使用谷歌地圖'callback'功能。它調用一旦谷歌地圖腳本加載的方法。 –

回答

3

您推遲谷歌圖書館有,所以當LoadGoogle()運行,該庫已不一定是加載。

2種方式去了解它:

  • 爲了進行測試,去除異步/推遲從包括。

  • 對於生產,請確保您的自定義腳本在加載其他所有內容後運行。做到這一點的方法是使用google提供的回調函數,因此腳本在加載時調用LoadGoogle函數。

<script src="http://maps.google.com/maps/api/js?key=AIzaSyAdXcTNKKaje1AtGQq32SwOMJ5Um-EE5GU&callback=LoadGoogle" async="async" defer="defer" type="text/javascript"></script>

在腳本

然後,不叫LoadGoogle()

Reference

+0

嘗試刪除推遲但不工作 – Samsam

+0

請參閱編輯回調參數和參考教程的說明 – xShirase

+0

感謝您的答覆。現在我沒有得到任何錯誤,但地圖不顯示。 – Samsam