我有以下服务可启动Google map :
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");
}]);
如您所见,我从
mapService.initialize(/**/)
调用了app.run
,但得到了异常: Uncaught TypeError: Cannot read property 'offsetWidth' of null
从其他帖子中可以看出,谷歌 map 仍然没有渲染,我需要等到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>
从 Controller 行:
mapService.initialize("heatmapAreaA"); works fine.
谢谢,
最佳答案
我无法对其进行测试,但是我想是您的html View 尚未完全由Angular编译,因此Google Maps找不到要在其中显示 map 的div。
mapService.initialize("heatmapAreaA");
在您的 View 中调用 Controller ,然后将调用置于$ timeout中:
$timeout(function(){
mapService.initialize("heatmapAreaA");
});
这样,在 Controller 运行并且 View 已编译之后,将触发该调用。