等待条件为真?

7 浏览
0 Comments

等待条件为真?

我在JavaScript中使用navigator.geolocation.watchPosition,我想找到一种方法来处理用户可能在watchPosition找到位置之前提交依赖于位置的表单的情况。

理想情况下,用户会定期看到“等待位置”的消息,直到位置被获取,然后表单会提交。

然而,鉴于JavaScript缺乏wait函数,我不确定如何实现这一点。

当前代码:

var current_latlng = null;
function gpsSuccess(pos){
    //console.log('gpsSuccess');  
    if (pos.coords) { 
        lat = pos.coords.latitude;
        lng = pos.coords.longitude;
    }
    else {
        lat = pos.latitude;
        lng = pos.longitude;
    }
    current_latlng = new google.maps.LatLng(lat, lng);
}
watchId = navigator.geolocation.watchPosition(gpsSuccess,
                  gpsFail, {timeout:5000, maximumAge: 300000});
$('#route-form').submit(function(event) {
    // 用户提交表单,我们需要他们的位置...
    while(current_location==null) {
        toastMessage('等待您的位置...');
        wait(500); // 我应该使用什么替代?
    }
    // 继续找到位置...
});

0