我正在开发一个使用GPS的小型网络应用程序。它使用Javascript来完成此任务。我在做什么:
这可能与异步有关吗?我对这个功能很陌生,任何帮助都将不胜感激!
// global variables
var positionCoords = {};
positionCoords['latitude'] = null;
positionCoords['longitude'] = null;
/*
on document ready, excecute
*/
$(document).ready(function() {
getGeolocation();
console.log(positionCoords);
});
/*
check if geolocation is supported and allowed, get coordinates
*/
function getGeolocation() {
if (navigator.geolocation) {
// geolocation is available
navigator.geolocation.getCurrentPosition(
function(position) {
// get coordinates
positionCoords['latitude'] = position.coords.latitude;
positionCoords['longitude'] = position.coords.longitude;
return true;
},
function(error){
handleGeolocationErrors(error);
return false;
}
);
} else {
// geolocation is not available
console.log("Browser does not support geolocation services.");
return false;
}
}
答案 0 :(得分:0)
由于 ASYNC 调用,您需要将函数回调传递给getGeolocation
,然后,您将调用它,如下所示:
$(document).ready(function() {
getGeolocation(function(coords){
console.log(coords);
//====The resof your code which dependent on `coords` SHALL be here
//......
},function(err){console.log(err)});
});
为了能够像上面那样调用它,你需要通过传递两个参数来修改getGeolocation
的实现:
/*
check if geolocation is supported and allowed, get coordinates
*/
function getGeolocation(fnsuccess,fnerror) {
if (navigator.geolocation) {
// geolocation is available
navigator.geolocation.getCurrentPosition(
function(position) {
if(typeof fnsuccess==='function'){
fnsuccess.call(null,position.coords); //--Call CallBack On Success
}
},
function(error){
if(typeof fnerror ==='function'){
fnerror.call(null,error); //--Call CallBack On Error
}
}
);
} else {
// geolocation is not available
console.log("Browser does not support geolocation services.");
return false;
}
}
DEMO会要求您分享您的位置,如果您接受,请检查浏览器的控制台,您将获得Coords
预期