问题
I have the following lines of code. Everything works except for setting the variable "UserLocation" and printing it to the console. My goal is to get the coordinates I find in the showPosition() function as a global variable that can be accessed anywhere, because I will be using them a lot and for many purposes.
What am I missing here? I've tried setting the coordinates variable inside showPosition to a global variable, tried returning the variable, etc. The only way I can get those coordinates out of that function as of now is to pass it as a parameter to a whole other function which I don't want to do.
if (navigator.geolocation) {
var UserLocation = navigator.geolocation.getCurrentPosition(showPosition);
console.log(UserLocation); // This doesn't work and gives me "undefined"
} else {
alert("Geolocation is not supported by this browser");
}
function showPosition(position) {
var coordinates = new Array();
coordinates.push(Math.floor(position.coords.latitude));
coordinates.push(Math.floor(position.coords.longitude));
console.log(coordinates) // This works
return coordinates;
}
回答1:
navigator.geolocation.getCurrentPosition
is asynchronous. As indicated in the comments, this means that UserLocation
will be undefined until getCurrentPosition
has completed.
Promises are excellent for dealing with asynchronous code. The following uses ECMA6 promises to set your global variable:
function getUserLocation() {
return new Promise(function(resolve, reject) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(resolve);
} else {
reject("Geolocation is not supported by this browser")
}
});
}
function showPosition(position) {
var coordinates = new Array();
coordinates.push(Math.floor(position.coords.latitude));
coordinates.push(Math.floor(position.coords.longitude));
console.log(coordinates) // This works
return coordinates;
}
function setGlobalCoordsAndAlert(coordinates) {
window.coordinates = coordinates;
alert(coordinates);
}
getUserLocation()
.then(showPosition)
.then(setGlobalCoordsAndAlert)
.catch(function(err) {
console.log(err);
});
ECMA6 promises aren't available in older browsers, so check out a polyfill if you're worried about compatibility.
- Promise documentation.
- Promise polyfill.
来源:https://stackoverflow.com/questions/38287407/cant-return-get-access-to-a-variable-inside-a-function