2011-11-24 52 views
1

我在android開發中使用phonegap。我寫了PoC,但是我無法弄清楚爲什麼它不會改變profile變量的緯度。其實Android中的Phonegap onDeviceReady函數

alert(profile.latitude); 

geoCode.setLocation(); 

這裏奔跑是我的代碼;

document.addEventListener("deviceready", onDeviceReady, false); 

var profile = { 
    name: "", 
    id: "red", 
    latitude: "xx", 
    longtitude: "", 
    setCoordinates: function (latit, longt) { 
     this.latitude = latit; 
     this.longtitude = longt; 
    } 
}; 

var geoCode = { 
    onSuccess: function (position) { 
     profile.latitude = position.coords.latitude; 
    }, 

    onError: function (error) { 
    }, 

    setLocation : function() { 
     navigator.geolocation.getCurrentPosition(this.onSuccess, this.onError); 
    } 
}; 

// Wait for PhoneGap to load 
// 

function onDeviceReady() { 

    geoCode.setLocation(); 
    //alert("2"); 
    alert(profile.latitude); 
}; 

在此先感謝

回答

1

navigator.geolocation.getCurrentPosition是一個異步函數。您需要執行以下操作:

var geoCode = { 


setLocation : function (callback) { 

    onSuccess: function (position) { 
     callback(position.coords.latitude); 
    }, 

    onError: function (error) { 
    }, 
    navigator.geolocation.getCurrentPosition(onSuccess, onError); 
} 

}; 

// Wait for PhoneGap to load 
// 

function onDeviceReady() { 

    geoCode.setLocation(function(latitude) { 
     alert(latitude); 
    }); 
}; 
0

很簡單這是因爲調用navigator.geolocation.getCurrentPosition()是一個異步調用。從而繼續執行程序,您會看到警報。在警報顯示之後的某個時候,geoCode類的onSuccess調用稱爲更新profile.latitude值。