I am loading a Google map and when I navigate to /map it loads the the markers to populate the map. The problem is that the rest of the javascript runs and executes before the markers have loaded. What I thought would solve it would be to return a promise in the factory that retrieves the map data. This didn't work though.
Can anyone advise on what I'm doing wrong?
In the console I see this:
angular.js:13920 TypeError: Cannot read property 'lat' of undefined
at Object.link (http://localhost/logintest/js/app.js:586:55)
Line 586 refers to this line (in the directive):
center: new google.maps.LatLng(lastElement.lat, lastElement.lon),
I get the lastElement like so:
var lastElement = scope.arrLocations[scope.arrLocations.length - 1];
Factory:
app.factory('map', ['$q', function($q){
var map={};
var mapInfoItems=[];
map.getMapInfo = function() {
var deferred = $q.defer();
var mapitems = firebase.database().ref('mapinfo/'+firebase.auth().currentUser.uid);
mapitems.on('child_added', function(snapshot){
mapInfoItems.push(snapshot.val());
deferred.resolve(mapInfoItems);
});
return deferred.promise;
};
return map;
}]);
Controller:
app.controller('mapController', ['$scope', 'map', function($scope, map){
$scope.myLocations = {};
$scope.arrLocations = [];
$scope.mapLocations = map.getMapInfo();
for(var i=0; i<$scope.mapLocations.length; i++){
$scope.myLocations.title = $scope.mapLocations[i].name;
$scope.myLocations.content = $scope.mapLocations[i].message;
$scope.myLocations.lat = $scope.mapLocations[i].lat;
$scope.myLocations.lon = $scope.mapLocations[i].lon;
$scope.arrLocations.push($scope.myLocations);
}
}]);
html:
<div ng-controller="mapController">
<my-map get-map-fn="getMap()"></my-map>
</div>
arrLocations. Let's log the prior step in the console and see what it looks like. Maybeconsole.log($scope.myLocations);