Javascript Navigator.geolocation
Javascript Navigator.geolocation
我正在尝试 return position.coords.latitude 和经度作为变量在代码的其他地方使用。我如何获得 return 可用变量的函数?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var values = [lat, lon];
return values;
});
}
console.log(values);
您应该使用回调方法。
读一读:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) { // success callback
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
var values = [crd.latitude, crd.longitude];
doSomethingWithCoordinateValues(values);
};
function doSomethingWithCoordinateValues(coords) {
// do something with 'coords'
}
function error(err) { // error callback
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
您还可以阅读这篇 answer 的文章,其中指出:
If an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.
我正在尝试 return position.coords.latitude 和经度作为变量在代码的其他地方使用。我如何获得 return 可用变量的函数?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var values = [lat, lon];
return values;
});
}
console.log(values);
您应该使用回调方法。
读一读:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) { // success callback
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
var values = [crd.latitude, crd.longitude];
doSomethingWithCoordinateValues(values);
};
function doSomethingWithCoordinateValues(coords) {
// do something with 'coords'
}
function error(err) { // error callback
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
您还可以阅读这篇 answer 的文章,其中指出:
If an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.