2016-12-15 6 views
0

안녕하세요, 아래 코드로 지오 코더를 사용하여 경도 & 경도를 얻으려고합니다. 나는이 글로벌 수준에서 변수를 postions 선언 한배열 길이가 0이지만 컨트롤에 표시됩니다.

var tempArr = []; 
var posObj = {}; 

_.each(vm.result, function(data) { 
    var tempPosArr = []; 
     getLatitudeLongitude(function (result) { 
     var tempPosArr = []; 
      tempPosArr.push(result.geometry.location.lat()); 
      tempPosArr.push(result.geometry.location.lng()); 
      var posObj = { 
       pos : tempPosArr 
      }; 
      positions.push(posObj); 
     }, data.location) 
     console.log(positions); 
}); 

console.log(positions.length); 

아래로

function getLatitudeLongitude(callback, address) { 
    geocoder = new google.maps.Geocoder(); 
    if (geocoder) { 
     geocoder.geocode({ 
      'address': address 
     }, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       callback(results[0]); 
      } 
     }); 
    } 
} 

내 API 성공 기능입니다. 데이터가 푸시되고 있지만 결과는 아래로 떨어지고 있습니다.

enter image description here

그것은 모든 위도, 경도를 가지고 및 생성 온도의 Obj도 밀어하지만 외부에서, 결과는 그림과 같이됩니다.

+0

는 시간이 배열을 검사하는 것이 가능하다 그것은 아이가 없었고 나중에 신이 추가 되었습니까? @ user422831 – Yaser

답변

0

네, 그것은이다,이 기능 때문에 : getLatitudeLongitude 서버에서 어쩌면 데이터를 얻을 당신이

예에 대한 약속을 사용해야합니다 :

var tempArr = []; 
var posObj = {}; 
var defer = $q.defer(); // inject the $q service to add defer 
_.each(vm.result, function(data) { 
    var tempPosArr = []; 
     getLatitudeLongitude(function (result) { 
     var tempPosArr = []; 
      tempPosArr.push(result.geometry.location.lat()); 
      tempPosArr.push(result.geometry.location.lng()); 
      var posObj = { 
       pos : tempPosArr 
      }; 
      positions.push(posObj); 
      defer.resolve(positions);// now you resolve the promise 
     }, data.location) 
     console.log(positions); 
}); 

//console.log(positions.length); 
// you can catch the promise here when it resolved 
defer.promise.then(function(positions){ 
console.log(positions) 
});