2014-01-21 26 views
3

我有以下服務從「跑」的方法谷歌地圖,啓動谷歌地圖:獲取錯誤無法讀取屬性「offsetWidth」時嘗試發起角

app.service('mapService', ['$q', '$rootScope', function($q, $rootScope) { 
      var self = this; 
      var geocoder = new google.maps.Geocoder(); 
      var streetViewService = new google.maps.StreetViewService(); 
      self.map = false; 
      self.panorama = false; 
      self.center = null; 

      self.initialize = function(map_id) { 
        var options = { 
          center: new google.maps.LatLng(0, 0), 
          zoom: 3, 
          scaleControl: true, 
          mapTypeId: google.maps.MapTypeId.ROADMAP 
        }; 
        self.map = new google.maps.Map(document.getElementById(map_id), options); 
        // ^^^ here get error 
        }; 
    .... 

app.js的樣子:

var app = angular.module('cntsApp', []); //['AngularGM'] 

app.config(['$routeProvider', function($routeProvider) { 
       $routeProvider.when('/mapboard', {templateUrl: config.base_url + 'app/partials/cnts.html', controller: 'CntsCtrl'});     
     }]); 


app.run([ 
    '$rootScope', 
    '$window', 
    'mapService', 
    function($rootScope, $window, mapService) { 

     mapService.initialize("heatmapAreaA"); 

     }]); 

正如你可以看到我稱之爲從app.runmapService.initialize(/**/),但得到的異常:

Uncaught TypeError: Cannot read property 'offsetWidth' of null 

從其他帖子來看,它意味着谷歌地圖仍然沒有渲染,我需要等到DOM完成。

我該如何實現這一點?

[編輯]

HTML

<div ng-controller="CntsCtrl"> 

    <div class="container" style="width: 96%"> 
     <div class="row clearfix"> 
      <div class="col-md-12 column"> 
       <div class="row clearfix"> 
        <div class="col-md-2 column"> 
         Config 
        </div> 
        <div class="col-md-6 column"> 
         <div id="heatmapAreaA" ></div> 
        </div> 
        <div class="col-md-4 column"> 
         Chart 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 

從控制線:mapService.initialize("heatmapAreaA"); works fine.

感謝,

+0

你們每個人都有這個工作,因爲我有同樣的問題? –

回答

2

我無法測試它,但我的猜測是你的view html沒有完全由Angular編譯,因此Goog樂地圖無法找到你的div來顯示地圖嘗試把

mapService.initialize("heatmapAreaA"); 

呼叫您的視圖控制器,並把該呼叫並在$超時:

$timeout(function(){ 
    mapService.initialize("heatmapAreaA"); 
}); 

這樣,在控制器運行並且您的視圖已編譯後,調用會被觸發。

相關問題