如何获取API并使用在另一个函数中获得的值



我正在使用ES6的新获取接口来获取ISS(国际空间站(的地理位置,并在谷歌地图中进行渲染,但我不知道如何将ISS_position的值传递给其他函数。

export async function currentPosition() {
const fetchResult = fetch('http://api.open-notify.org/iss-now.json');
const response = await fetchResult;
const iss_position = await response.json();
}
export function initMap() {
let map = new google.maps.Map(document.getElementById('map'), {
center: iss_position,
zoom: 5,
});
let marker = new google.maps.Marker({
position: iss_position,
map: map,
});
}
currentPosition();
initMap();
async function currentPosition() {
const fetchResult = fetch('http://api.open-notify.org/iss-now.json');
const response = await fetchResult;
const iss_position = await response.json();
// Calling initMap with iss_position
initMap(iss_position);
}
function initMap(iss_position) {
let map = new google.maps.Map(document.getElementById('map'), {
center: iss_position,
zoom: 5,
});
let marker = new google.maps.Marker({
position: iss_position,
map: map,
});
}
currentPosition();
// Please check if this write way to export multiple things or not.
// I'm a NodeJS developer and this is how we do in node.
export = {
currentPosition,
initMap
}

这应该有效:

async function currentPosition() {
const fetchResult = fetch('http://api.open-notify.org/iss-now.json');
const response = await fetchResult;
const data = await response.json();
const { latitude, longitude } = data.iss_position;
initMap(latitude, longitude);
}
function initMap(latitude, longitude) {
let map = new google.maps.Map(document.getElementById('map'), {
center: { lat: latitude, lng: longitude },
zoom: 5,
});
let marker = new google.maps.Marker({
position: { lat: latitude, lng: longitude },
map: map,
});
}
currentPosition();
export { currentPosition, initMap };

相关内容

  • 没有找到相关文章

最新更新