如何在用户授权后启动navigator.geolocation超时计时器?

时间:2016-10-14 11:18:08

标签: javascript jquery geolocation

如您所知,HTML Geolocation必须由用户通过浏览器授权。我正在运行5秒的超时,并注意到如果用户需要更长时间才能点击接受(或拒绝),那么它将停止工作。有没有办法让用户点击Accept / Deny后启动计时器,而不是在调用函数时?

以下是我的称呼方式:

navigator.geolocation.getAccurateCurrentPosition(
         showPosition, showError, showProgress, 
         {desiredAccuracy:1500, maxWait:5000}
);

功能:

navigator.geolocation.getAccurateCurrentPosition = function (showPosition, showError, showProgress, options) {
    var lastCheckedPosition,
        locationEventCount = 0,
        watchID,
        timerID;

    options = options || {};

    var checkLocation = function (position) {
        lastCheckedPosition = position;
        locationEventCount = locationEventCount + 1;
        // We ignore the first event unless it's the only one received because some devices seem to send a cached
        // location even when maxaimumAge is set to zero
        if ((position.coords.accuracy <= options.desiredAccuracy) && (locationEventCount > 1)) {
            clearTimeout(timerID);
            navigator.geolocation.clearWatch(watchID);
            foundPosition(position);
        } else {
            showProgress(position);
        }
    };

    var stopTrying = function () {
        navigator.geolocation.clearWatch(watchID);
        foundPosition(lastCheckedPosition);
    };

    var onError = function (error) {
        clearTimeout(timerID);
        navigator.geolocation.clearWatch(watchID);
        showError(error);
    };

    var foundPosition = function (position) {
        showPosition(position);
    };

    if (!options.maxWait)            options.maxWait = 5000; // Default 5 seconds
    if (!options.desiredAccuracy)    options.desiredAccuracy = 1500; // Default 1500 meters
    if (!options.timeout)            options.timeout = options.maxWait; // Default to maxWait

    options.maximumAge = 0; // Force current locations only
    options.enableHighAccuracy = true; // Force high accuracy (otherwise, why are you using this function?)

    watchID = navigator.geolocation.watchPosition(checkLocation, onError, options);
    timerID = setTimeout(stopTrying, options.maxWait); // Set a timeout that will abandon the location loop
};

0 个答案:

没有答案