4

I am using the following javascript to load google map into my angular.js web application. The map works fine when I am on the page and refresh; however, when I LINK TO THE PAGE from somewhere else in my application the map does not load. I believe this has something to do with the DOM listener is not registering a 'load' event, but, am not sure. I would appreciate help in solving this.

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); }); 

Solution courtesy of 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> 

1 Answer 1

6

Instead of trying to run the initialize function on load event you can try using ng-init

Add the initialize function to the scope:

$scope.initialize = function(){ //code goes here }; 

Then call initialize function when the controller is initialized by angular

<div data-ng-controller="BarsController" data-ng-init="initialize()"></div> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.