jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 如何使用延迟对象通过HTML5 Geolocation API检索经度和纬度?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用 HTML5 GeoLOCATIOn API来检索我的经度和纬度,并使用jQuery Deferred对象管理请求.

这是我的代码的样子:

var geoLOCATIOn = {

    getLOCATIOn: function() {

        // create deferred object
        var deferred = $.Deferred();

        // if geo LOCATIOn is supported
        if(navigator.geoLOCATIOn) {

            // get current position and pass the results to this.geoLOCATIOnsuccess or time out after 5 seconds if it fails
            navigator.geoLOCATIOn.getCurrentPosition(this.geoLOCATIOnsuccess,this.geoLOCATIOnError,{
                timeout: 5000
            });

        } else {

            // geo LOCATIOn isn't supported
            console.log('Your browser does not support Geo LOCATIOn.');
        }

    },geoLOCATIOnsuccess: function(position) {

        // resolve deffered object
        deferred.resolve(position.coords.latitude,position.coords.longitudE);

        // return promise
        return deferred.promise();
    },geoLOCATIOnError: function() {
        console.log('Geo LOCATIOn Failed.');
    }

};

这是我的Deferred对象:

$.when(geoLOCATIOn.getLOCATIOn()).then(function(data,textStatus,jqXHR) {

    console.log(data);

});

我期望then()回调返回经度和纬度,但相反,我得到延迟的错误是未定义的.我认为它与我定义延迟对象的范围有关,但我不确定.我错过了什么?

解决方法

迈克尔在阅读了Hackaholic的答案和你自己的答案之后,都将在处理成功返回的数据方面工作,但错误可以更好地处理.

如果navigator.geoLOCATIOn.getCurrentPosition()失败,它会将一个可能提供信息的PositionError对象传递给它的错误处理程序.这个对象可以在承诺链中传递并在调用函数中处理,在两个答案中都被忽略.

同样,承诺拒绝也可以用来传递你自己的“你的浏览器不支持地理位置”错误的承诺链.

var geoLOCATIOn = {
    getLOCATIOn: function() {
        var deferred = $.Deferred();
        if(navigator.geoLOCATIOn) {
            // geo LOCATIOn is supported. Call navigator.geoLOCATIOn.getCurrentPosition and :
            // - resolve the promise with the returned Position object,or
            // - reject the promise with the returned PositionError object,or
            // - time out after 5 seconds
            navigator.geoLOCATIOn.getCurrentPosition(deferred.resolve,deferred.reject,{ timeout: 5000 });
        } else {
            //geo LOCATIOn isn't supported
            //Reject the promise with a suitable error message
            deferred.reject(new Error('Your browser does not support Geo LOCATIOn.'));
        }
        return deferred.promise();
    } 
};

忽略注释,这非常紧凑,并注意geoLOCATIOn.getLOCATIOn()如何不尝试处理错误,但使它们可用于调用函数错误处理程序.

现在,$.when()不是必需的,因为你的geoLOCATIOn.getLOCATIOn()函数返回一个具有自己的.then()方法的promise.没有$.when(),它已经“可以”了.

geoLOCATIOn.getLOCATIOn().then(function(position) {
    console.dir(position);
}).fail(function(err) {
    console.error(err);
});

因此,您充分利用承诺处理成功或失败的能力.

大佬总结

以上是大佬教程为你收集整理的jquery – 如何使用延迟对象通过HTML5 Geolocation API检索经度和纬度?全部内容,希望文章能够帮你解决jquery – 如何使用延迟对象通过HTML5 Geolocation API检索经度和纬度?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。