2011-11-24 51 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值。