我使用以下javascript将google地图加载到我的angular.js网络应用程序中。当我在页面上并刷新时,地图工作正常;但是,当我从我的应用程序中的其他位置链接到页面时,地图不会加载。我相信这与DOM监听器没有注册“负载”有关。事件,但是,我不确定。我很感激帮助解决这个问题。
authApp.controller('BarsController', function($scope, $rootScope, BarService) {
$scope.currentUser = Parse.User.current();
$scope.title = $rootScope.title;
function initialize(){
var mapOptions = {
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$scope.map = map;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
$scope.map.setCenter(pos);
//Set myLocation Pin
var marker = new google.maps.Marker({
position: pos,
map: $scope.map,
title: 'My Location',
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
});
}), function(error){
console.log('Unable to get location: ' + error.message);
};
}
};
google.maps.event.addDomListener(window, 'load', initialize);
});
解决方案由DMullings提供:
authApp.controller('BarsController', function($scope, $rootScope, BarService) {
$scope.currentUser = Parse.User.current();
$scope.title = $rootScope.title;
$scope.initialize = function(){
var mapOptions = {
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$scope.map = map;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
$scope.map.setCenter(pos);
//Set myLocation Pin
var marker = new google.maps.Marker({
position: pos,
map: $scope.map,
title: 'My Location',
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
});
}), function(error){
console.log('Unable to get location: ' + error.message);
};
}
};
});
HTML:
<div data-ng-controller="BarsController" data-ng-init="initialize()">
//HTML Content Here
</div>
答案 0 :(得分:6)
您可以尝试使用load
ng-init
事件上运行初始化函数
将initialize
函数添加到范围:
$scope.initialize = function(){
//code goes here
};
然后在通过angular
初始化控制器时调用initialize函数<div data-ng-controller="BarsController" data-ng-init="initialize()"></div>