转换lat&在phonegap中长到javascript变量

时间:2013-03-13 16:39:48

标签: javascript cordova asynchronous

我遇到了一个我似乎无法弄清楚的问题。 我正在使用phonegap尝试获取当前的纬度和经度,并将值分配给变量。

我将在应用程序中的多个位置使用纬度和经度,因此我需要将其分配给我可以在其他地方使用的变量。

在此设置中,html输出为“undefined”。

我确定这与我错过的javascript和async有关...有什么帮助吗?

/******************** Life Cycle ************************/

function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

/******************** Device is Ready ************************/

function onDeviceReady() {


/******************** Geo Info ************************/

    // Variables
    var currentLat;
    var currentLon;
    var geoWatchID = 0;

    // get current geo location
    if (geoWatchID == 0) {
        var geoOptions = {maximumAge: 3000, enableHighAccuracy: true};
        geoWatchID = navigator.geolocation.watchPosition(onSuccess, onError, geoOptions);

        function onSuccess(position) {
            currentLat = position.coords.latitude;
            currentLon = position.coords.longitude;
        }

        function onError(error) {
            alert('code: ' + error.code + '\n' +
                  'message: ' + error.message + '\n');
        }

    } else {
        navigator.geolocation.clearWatch(geoWatchID);
        geoWatchID = 0;
    }

    // display the current latitude and longitude w/ jquery
    $('#currLat').html(currentLat);
    $('#currLon').html(currentLon);

} // END device is ready 

之前有人使用过吗?

1 个答案:

答案 0 :(得分:3)

这是因为onSuccess仅在jQuery语句之后被调用,所以请尝试

    function onSuccess(position) {
        currentLat = position.coords.latitude;
        currentLon = position.coords.longitude;

        // display the current latitude and longitude w/ jquery
        $('#currLat').html(currentLat);
        $('#currLon').html(currentLon);
    }

编辑:

    function onSuccess(position) {
        currentLat = position.coords.latitude;
        currentLon = position.coords.longitude;
        update();    
    }

    function update(){
        // display the current latitude and longitude w/ jquery
        $('#currLat').html(currentLat);
        $('#currLon').html(currentLon);
    }