我正在尝试从getCurrentLocation()方法获取一个对象,然后在getUserAddressBy()方法上使用该对象的坐标(position.coords.latitude,position.coords.longitude)。我从app.js调用它,但是当我在其中控制台日志时,它得到一个未定义的值,当我在方法上控制台日志时,我得到了正确的对象。
有什么帮助吗?我是JavaScript编程的新手。
这是我的代码。
class GeoLocator {
constructor(city, country) {
this.keyUser = "";
this.city = city;
this.country = country;
}
async getUserAddressBy(lat, long) {
const location = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?
latlng=${lat},${long}&key=${this.keyUser}`);
const currentLoc = await location.json();
this.city = currentLoc.results[0].address_components[3].long_name;
this.country = currentLoc.results[0].address_components[5].short_name;
return { city: this.city, country: this.country };
}
getCurrentLocation() {
self = this;
return navigator.geolocation.getCurrentPosition(position => {
console.log(position);
return position;
});
}
}
// My app.js file
const currentLocation = new GeoLocator();
console.log(currentLocation.getCurrentLocation());
[getCurrentPosition
函数不会立即调用。
在Javascript中,许多操作都是异步完成的,这意味着该函数在操作完成之前就返回了,您以后必须通过以下任一方法来处理结果:* callback
函数在操作完成时被调用* Promise
在执行操作时被解析/拒绝完成。对于navigator.geolocation.getCurrentPosition
函数,它使用您提供的回调函数。这意味着当数据准备就绪时,将调用您作为调用参数提供的函数。