【发布时间】:2014-11-15 20:46:18
【问题描述】:
我想使用 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() 回调返回经度和纬度,但我得到deferred 未定义的错误。我认为这与我定义延迟对象的范围有关,但我不确定。我错过了什么?
【问题讨论】:
标签: jquery geolocation promise deferred