【发布时间】:2020-02-25 03:56:36
【问题描述】:
我有一个小型天气应用程序,它首先从用户的浏览器获取位置 并将 lat 和 lon 存储在类的对象中。 mathod getAdress() 调用 api 将 lat 和 lon 值转换为地址。
这是我的课
import axios from 'axios';
import { keyApp , keyMap , link} from '../config';
export default class Location {
constructor(id){
this.id = id;
}
async getLocation() {
if(navigator.geolocation){
(navigator.geolocation.getCurrentPosition(async position => {
this.lat = await position.coords.latitude;
this.lon = await position.coords.longitude;
}));
}
else {
console.log('Not able to get location..');
}
}
async getAddress() {
try {
const address = await axios(`https://us1.locationiq.com/v1/reverse.php?key=${keyMap}&lat=${this.lat}&lon=${this.lon}&format=json`);
this.address = address;
}
catch(e) {
console.log(e);
}
}
这是 index.js 文件
import Location from './modules/Location';
window.current = {}; //Testing purpose
const controlLocation = async () => {
current.location = new Location(1);
await current.location.getLocation();
await current.location.getAddress();
}
window.addEventListener('load' , controlLocation);
错误是方法获取地址尝试获取数据并调用 api 而不等待 lat 和 lon 值。 这是错误,值未定义
GET https://us1.locationiq.com/v1/reverse.php?key=MY_Private_KEY&lat=undefined&lon=undefined&format=json 400
【问题讨论】: