[英]Javascript: Geolocation values in global variable
I'm working on a little web application which uses GPS. 我正在研究一个使用GPS的小型网络应用程序。 It uses Javascript to accomplish this. 它使用Javascript完成此任务。 What I'm doing: 我在做什么:
Could this has something to do with asynchronously? 这可能与异步有关吗? I'm quite new to this feature, any help would be appreciated! 我对这个功能还很陌生,任何帮助将不胜感激!
// 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;
}
}
Since it is ASYNC call, you need to pass function-callback to getGeolocation
, then , you will call it like the follwong : 由于它是ASYNC调用,因此您需要将function-callback传递给getGeolocation
,然后将像follwong一样调用它:
$(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)});
});
To be able to call it like the above , you need to modify the implementation of getGeolocation
by passing it two parameters : 为了能够像上面那样调用它,您需要通过传递两个参数来修改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;
}
}
the DEMO will ask you to share your location , if you accept , check the console of your browser , you will get Coords
as you expect DEMO会要求您分享您的位置,如果您接受,请检查浏览器的控制台,您将按预期获得Coords
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.