2013-03-13 77 views
1

我遇到了一个我似乎无法解决的问题。 我使用phonegap来尝试获取当前的经度和纬度并将值分配给变量。在手机中将纬度和长度转换为javascript变量

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

在此设置中,html输出为“未定义”。

我敢肯定,这与JavaScript和异步,我失踪...有什么帮助吗?

/******************** 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 

以前有人用过这个吗?

+0

它看起来像我没有宣布经纬度为全局变量。 – Troy 2013-03-13 19:08:24

回答

3

这是因为onSuccess只jQuery的statments后调用,所以尽量

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); 
    } 
+0

其实,这不是我正在寻找的...我试图获取变量currentLat和currentLon在onSuccess之外使用。 jquery标记仅用于显示它是否工作。 – Troy 2013-03-13 16:59:37

+0

我明白了。但是在执行你写的jQuery语句时,'currentLat'和'currentLon'都是未定义的。然后,'onSuccess'被事件调用,然后变量将具有eveywhere的值。 – Diode 2013-03-13 17:29:44

+0

请检查更新后的答案。希望能帮助你理解它。 – Diode 2013-03-13 17:31:54