2016-10-08 28 views
0

我正在加載Google地圖,當我導航到/地圖時,它會加載標記以填充地圖。問題是JavaScript的其餘部分在加載標記之前運行並執行。我認爲解決這個問題的方法是在檢索地圖數據的工廠返回一個承諾。這雖然沒有奏效。我的角廠承諾有什麼問題?

任何人都可以建議我做錯了什麼?

在控制檯中我看到這一點:

angular.js:13920 TypeError: Cannot read property 'lat' of undefined 
at Object.link (http://localhost/logintest/js/app.js:586:55) 

586線是指這條線(該指令):

  center: new google.maps.LatLng(lastElement.lat, lastElement.lon), 

我得到了lastElement像這樣:

var lastElement = scope.arrLocations[scope.arrLocations.length - 1]; 

工廠:

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

控制器:

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> 
+0

是什麼控制檯說? –

+0

我已經添加了更多的細節。 – user1532669

+0

好吧,所以'arrLocations'的創建有些問題。讓我們在控制檯中記錄前一步,看看它的樣子。也許'console.log($ scope.myLocations);' –

回答

1

map.getMapInfo()返回的希望,但是,如果它返回控制器

而且你保持覆蓋的屬性數組你對待它for循環中的同一對象的相同對象,並將相同的對象引用推送到數組中。這意味着數組將結束與環中設置的最後一個值中的所有元素......因爲他們是一個對象的所有引用

更換

$scope.mapLocations = map.getMapInfo(); 

隨着

map.getMapInfo().then(function(locations){ 
    for(var i=0; i<locations.length; i++){ 
     // create new object each iteration 
     var obj ={ 
      title : locations[i].name, 
      content: locations[i].message, 
      // ... etc  
     }  

     $scope.arrLocations.push(obj); 
    }  
}); 
+0

這對我來說非常合理,看起來應該可以工作。我現在正在看看它,但我可能需要稍後回來,就像它在這裏的凌晨2點一樣。謝謝 :) – user1532669