2016-05-31 62 views
0

我一直在試圖解決這個問題,但沒有成功。我明白,getCurrentPosition()返回一個承諾,並在.then()函數中調用$ scope.map.center將工作。我也明白,$ scope在摘要循環中運行,並且它的屬性和對象在promise解決時更新。我對這一切都很陌生,我希望自己有道理。

這就是說,我完全喜歡瞭解發生了什麼,因爲console.log($ scope.map)按預期工作,{{map.center}}按預期顯示,但console.log(map.center)返回.then()函數之外的空對象。

在此先感謝您的幫助!

$scope.map = { 
 
      control: {}, 
 
      center: {}, 
 
      zoom: 16 
 
     }; 
 

 
    $geolocation.getCurrentPosition({ 
 
     timeout: 60000, 
 
     maximumAge: 250, 
 
     enableHighAccuracy: true 
 
    }).then(function(position) { 
 
     $scope.map.center.latitude = position.coords.latitude; 
 
     $scope.map.center.longitude = position.coords.longitude; 
 
    }); 
 

 

 
    //Output 
 
    
 
    console.log($scope.map); //returns full object including data within $scope.map.center 
 

 
    console.log($scope.map.center); //returns an empty object. I am looking to convert this to an array using lodash.
{{ map.center }} works fine and returns the coordinates of my current location

**編輯(控制檯的上載的圖像)**

This is what I see in the console. First object is $scope.map Second object is $scope.map.center

回答

0

getCurrentPosition完成後(異步)調用then函數並將數據發送回客戶端。這是您唯一可以可靠訪問其檢索的數據的地方。如果您正在進行異步調用,則必須使用then函數來訪問數據。這是電話發生後發生的事情。接下來的代碼(函數外部)在getCurrentPosition被調用後立即執行 - 而不是在完成時執行。

如果您只是尋找不同的地方來放置此代碼,您可以調用另一個函數以外的函數,並將位置對象傳遞給它。

$scope.map = { 
     control: {}, 
     center: {}, 
     zoom: 16 
    }; 

$geolocation.getCurrentPosition({ 
    timeout: 60000, 
    maximumAge: 250, 
    enableHighAccuracy: true 
}).then(processMap(position)) 

function processMap(position) { 
    $scope.map.center.latitude = position.coords.latitude; 
    $scope.map.center.longitude = position.coords.longitude; 
    console.log($scope.map); 
    console.log($scope.map.center); 
}; 

如果您正在尋找有關asynchonous呼叫的詳細信息,請參閱這樣的解釋:

http://docs.apigee.com/api-baas/asynchronous-vs-synchronous-calls

+0

感謝您的詳細解答!原諒我,如果我錯過了你的解釋,但我想知道爲什麼$ scope.map首先工作。 – nubianrover

+0

它不是真的沒有,你只是得到你在控制器功能頂部創建的對象,或者可能部分完成了調用。 –

+0

在做了一些更多的檢查之後,我現在認爲它與HTML5地理位置返回稱爲座標的特殊對象類型有關。這會滿足我現在的好奇心。但是,那麼我可能是錯的。 – nubianrover

0

getCurrentPosition()呼叫是異步的。所以你的電話登錄$scope.map$scope.map.center只會返回你最初定義它們的東西。

數據將只在ajax調用完成時設置在範圍內。

+0

你說他們都應該回到我最初所定義的那樣。我對log $ scope.map的調用返回了完整的對象(包括保存在$ scope.map ['center']中的座標)。另一方面,我對$ scope.map.center的調用返回了一個空對象。這就是困擾我的東西。如果兩個都返回空對象,我會很好。 – nubianrover

+0

@nubianrover看起來您還需要調用''apply'''來確保所做的更改反映在範圍中。 http://stackoverflow.com/questions/23185619/how-can-i-use-html5-geolocation-in-angularjs – jtmingus