2012-09-28 30 views
0

我想寫,返回表示該設備的位置的對象的功能:我曾嘗試:我已經添加了註釋標記語句1和語句2。如果的PhoneGap:變量的作用域

function getDevicePosition() { 
    var positionObject; 
    if (isDeviceReady) { 
     navigator.geolocation.getCurrentPosition(function (position) { 

      positionObject = position; 
      console.log('location updated'); 
      console.log(positionObject.coords.longitude);//1. works 
     }, function (err) { 
      console.log('Failed to get device position' + err); 
      return null; 
     }); 

    } else { 
     warnUser(); 
     return null; 
    } 
    console.log(positionObject.coords.longitude);//2. doesnt work as positionObject is null. 
    return positionObject; 
} 

公告我在語句1中初始化了位置對象。爲什麼它在語句2中未定義?

+0

如果是這樣的話,我該如何從回調中返回位置對象,以便它從getDevicePosition()函數返回。 –

+0

你不能。在回調中做你需要做的事情。你可以讓你的'getDevicePosition'函數接受它自己的回調函數,然後從'getCurrentPosition'回調中調用它。 –

回答

1

因爲getCurrentPosition異步方法。標記爲2的行將在回調函數有機會執行之前運行,因此positionObject仍然是undefined

您需要將所有取決於positionObject的代碼在回調中移動到getCurrentPosition

1

navigator.geolocation.getCurrentPosition()的調用是異步的,所以該函數的其餘部分的執行不會等到它完成。

所以你的功能是在執行基本減少到這一點:

function getDevicePosition() { 
    var positionObject; 
    if (isDeviceReady) { 
     // trigger some asynch function ... 
    } else { 
     warnUser(); 
     return null; 
    } 
    console.log(positionObject.coords.longitude); 
    return positionObject; 
} 

從這個代碼應該是很明顯的,即在點,你的代碼達到console.log()你positionObject沒有設置,從而導致錯誤。

編輯

關於你的評論。這樣的任務的一般設計原則如下:

// original function (triggered by a button or whatever) 
function trigger() { 
    // do some calculations before 

    // trigger the position-retrival 
    navigator.geolocation.getCurrentPosition(function (position) { 
    // get the position 
    // ... 

    // call the handling function 
    doStuff(position); 
    }); 
} 

// the function to do stuff based on the position 
function doStuff(position) { 
// ... 
} 
+0

如果是這樣的話,我該如何從回調中返回位置對象,以便它從getDevicePosition()函數返回。 –

+0

@ user1476075你基本上不能。這裏的設計原則是從回調中觸發一個函數,該函數處理所有相關的代碼。 – Sirko