我正在使用以下JavaScript将google map加载到我的angular.js Web应用程序中。当我在页面上并刷新时,地图工作正常;但是,当我从应用程序中的其他位置链接到页面时,地图不会加载。我相信这与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>
除了尝试在load
事件上运行初始化函数外,您可以尝试使用ng-init
将initialize
函数添加到范围:
$scope.initialize = function(){
//code goes here
};
然后在通过角度初始化控制器时调用初始化函数
<div data-ng-controller="BarsController" data-ng-init="initialize()"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句