【发布时间】:2021-10-06 15:57:45
【问题描述】:
我的目标是在另一个文件中创建一个函数来导入“getGeoLocation.ts”,这就是代码:
export default function getGeoLocation () {
getLocationPromise.then((location:any) => {
console.log(location);
return location;
}).catch((err) => {
return err;
})
}
let getLocationPromise = new Promise((resolve, reject) => {
function success (position:any) {
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude})
}
function error(err:any) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options)
} else {
reject("your browser doesn't support geolocation API")
}
})
我也尝试过我在 MDN 中找到的 non-promise 版本:
export default function getLocation() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function error(err:any) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
function success(pos:any) {
var crd = pos.coords;
return crd;
console.log('Sua posição é:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`Precisão de ${crd.accuracy} metros.`);
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
alert("Geo Location not supported by browser");
}
}
两者都有相同的问题,我可以“console.log(location)”但不能“return location;” 调用另一个组件(下面的示例),就像我在任何其他返回对象的函数中所做的那样,为什么?
import getGeoLocation from '../utils/getGeoLocation';
const location = getGeoLocation();
console.log(location);
【问题讨论】:
标签: reactjs typescript geolocation progressive-web-apps