2015-02-10 53 views
1

我很新,需要js,我已經嘗試了所有可能在谷歌地圖上找到的有關谷歌地圖和需要js的東西。其他一切都可以在我的頁面,但谷歌地圖,如果我刷新頁面谷歌地圖顯示正常,但在瀏覽頁面時不會。無法讓Google地圖與requirejs一起工作

這裏是我的main.js

require(['jquery','semantic','gmap'],function($,sm,gmap){ 
function initGMap(){ 
     console.log('Initiating google maps'); 
     //please ignore 'Info' 
     var myMap = new gmap.Map(document.getElementById('gmap-canvas'),{ 
       center: new gmap.LatLng(Info.lat, Info.lon), 
       zoom: 15, 
       mapTypeId: gmap.MapTypeId.ROADMAP 
     }); 

     var infowindow = new gmap.InfoWindow({ 
      content: Info.contStr 
     }); 

     var marker = new gmap.Marker({ 
      position: new gmap.LatLng(Info.lat, Info.lon), 
      map: myMap, 
      title: 'My Title', 

     }); 

     infowindow.open(myMap, marker); 

     gmap.event.addListener(marker, 'click', function() { 
      infowindow.open(myMap,marker); 
     }); 

     $('#gmap-canvas').on('load',function(){ 
      gmap.event.trigger(myMap, 'resize'); 
      map.setZoom(myMap.getZoom()); 
     }) 

    } 
    gmap.event.addDomListener(window, 'load', initGMap); 
    $(document).bind("projectLoadComplete", initGMap); 

});

這是長什麼樣我gmap.js像

define('gmap',['async!https://maps.googleapis.com/maps/api/js?key=API_KEY'],function(){ 
return window.google.maps;}) 

沒有像

<script data-main="scripts/main" type="text/JavaScript" src="scripts/require.js"></script> 

比使用基本的腳本標籤requirejs本身的頁面上的任何其它腳本文件注:我使用semantic-ui,雖然如果有任何區別

任何建議都將得到滿足!

+0

我的要求需要一個嵌套定義GMAP的感覺。如果你把'console.log(gmap)'作爲你的'require'的第一行,那麼它會以'undefined'出現還是你得到這個對象? – Ohgodwhy 2015-02-10 02:43:37

+0

它顯示'未定義',但不是每次我加載時,幾乎每個備用負載 – Mani 2015-02-10 02:44:11

回答

0

google.maps.event.addDomListener(window, 'load', initGMap);是我的情況的罪魁禍首。事件'load'即使在頁面加載完成後也不會被觸發,所以不是在$(document).ready()內部使用這個語句我稱initGMap()

對於這種情況下的完整解決方案

gmap.js

define('gmap',['async!https://maps.googleapis.com/maps/api/js?key=API_KEY'],function(){ 

    self.mapStart = function(){ 


      console.log('Initiating google maps'); 


      var myMap = new google.maps.Map(document.getElementById('gmap-canvas'),{ 
        center: new google.maps.LatLng(Info.lat, Info.lon), 
        zoom: 15, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
      }); 

      var infowindow = new google.maps.InfoWindow({ 
       content: Info.contStr 
      }); 

      var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(Info.lat, Info.lon), 
       map: myMap, 
       title: 'My title', 

      }); 

      infowindow.open(myMap, marker); 

      google.maps.event.addListener(marker, 'click', function() { 
       infowindow.open(myMap,marker); 
      }); 

    } 

    return self;  
}) 

main.js

require(['gmap','jquery','semantic'],function(gmap,$,sm){ 


$(document).ready(function(){ 
     gmap.mapStart(); 
    }); 

});