地理定位超时回调触发是否收到响应的问题

时间:2012-03-16 13:29:45

标签: html5 geolocation timeout

我已根据此帖Geolocation feedback while accepting the request

为HTML5地理位置请求实施了计时器

但是我遇到一个问题,无论navigator.geolocation.received响应是否为真,都会调用计时器。也许我错过了一些非常明显的东西,但我看不清楚。

基本上,如果我获取地理位置信息,我会运行geo_success_action()功能,但在其他所有情况下(地理位置失败,接受位置共享超时或不存在html5地理位置支持)在浏览器中),我想运行geo_failure_action()函数。

然而,如果收集地理位置,我的geo_success_action()函数会被调用,然后当计时器用完时,geo_failure_action()也会被调用。

我假设在var中成功,navigator.geolocation.received = true的设置将传递给我的timedout函数,因此如果navigator.geolocation.received为真,则不会触发生成的函数。

有什么想法吗?

var succeed = function(obj) {
    navigator.geolocation.received = true;
    if (!navigator.geolocation.timedout) {
        geo_success_action( obj, json_url );
    }
};
var failed = function(obj) { 
    navigator.geolocation.received = true;
    if (!navigator.geolocation.timedout) {
        geo_failure_action( json_url );
    } else {
        geo_failure_action( json_url );
    }
};
var timedout = function() {
    navigator.geolocation.timedout = true; // could be used for other callbacks to trace if its timed out or not
    if (!navigator.geolocation.received){
        geo_failure_action( json_url );
        //alert('Timed Out');
    } else {
        null;
    }
}

// Extend geolocation object
if ( navigator.geolocation  ) {
    navigator.geolocation.retrievePermission = function retrievePermission(succeed,failed,options,timeout) {
        this.received = false;              // reference for timeout callback
        this.timedout = false;              // reference for other callbacks
        this.getCurrentPosition.apply(this,arguments);  // actual request

        // Trigger timeout with its function; default timeout offset 5000ms
        if ( timeout ) {
            setTimeout(timeout.callback,timeout.offset || 5000);
        }
    }

    // New location request with timeout callback
    navigator.geolocation.retrievePermission(succeed,failed,{},{
        offset: 6000, // miliseconds
        callback: timedout  
    });

// If geo-location not supported at all, do failure action
} else {
    geo_failure_action( json_url );
}

1 个答案:

答案 0 :(得分:0)

我没有测试过,但这应该可行

var timedout = function() {
    navigator.geolocation.timedout = true; 

    if( navigator.geolocation.received === undefined ) {
        navigator.geolocation.received = true;
    }

    if (!navigator.geolocation.received){
        geo_failure_action( json_url );
        //alert('Timed Out');
    } else {
        null;
    }
}