2012-10-09 55 views
0

Iam總共JS Newb,並試圖構建我的簡單JS代碼。目標是獲取用戶位置。結構JS - 變量爲空?

它的工作原理,但getUserCoordinates函數沒有返回值?我認爲這只是一個初學者的邏輯失敗?

var app = { 

geocoder: null, 

init: function() { 
    this.geocoder = new google.maps.Geocoder(); 
    coordinates = this.getUserCoordinates(); 
    console.log(coordinates); // empty?? 
    return; 
}, 

getUserCoordinates: function() { 

    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition( 

      function (coords) { 
       console.log(coords); // works Geocoder Object! 
       return coords; // the problem 
      }, // more code 

回答

2

不,這對初學者來說是一個很常見的錯誤。 getCurrentPosition方法是異步的(它需要一些時間來確定位置)並且不返回任何內容。完成後,它將調用您傳遞給它的callback函數 - 某些時候將會使用它。該值僅在該回調中可用,或者僅在那裏調用的函數中可用。

+0

感謝聽起來合乎邏輯,有沒有什麼好的解決方案呢? – opHASnoNAME

+0

您可以使用回調函數(您傳遞給getUserCoordinates方法),或者從代表該值的函數返回一個[Promise](http://wiki.commonjs.org/wiki/Promises)並使用回調函數內部。 – Bergi