Home > Enterprise >  how can i fetch random images from Astronomy photo of the day api in Javascript website
how can i fetch random images from Astronomy photo of the day api in Javascript website

Time:03-14

I tried to fetch current images from NASA's Astronomy Photo of the Day (APOD) But now i am trying to fetch images randomly without using dates Is it possible? If yes then how?

here's the code

const fetchAPOD = async () => {
  try {
    const response = await fetch("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
    const data = await response.json()
    displayData(data)
  } catch (error) {
    console.log(error)
  }
}

const displayData = data => {
  document.querySelector('.title').textContent = data.title
  document.querySelector('.date').textContent = data.date
  document.querySelector('.picture').src = data.url
  document.querySelector('.explanation').textContent = data.explanation
}

fetchAPOD()

which is working fine

all i want is to add feature to get images from the API randomly

CodePudding user response:

count A positive integer, no greater than 100. If this is specified then count randomly chosen images will be returned in a JSON array. Cannot be used in conjunction with date or start_date and end_date.

https://jsfiddle.net/mplungjan/pymfg2uv/

const imgDiv = document.getElementById("imageDiv");

fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=3`)
.then(response => response.json())
.then(data => {
  imgDiv.innerHTML = data.map(item => `<div>
 <h3 >${item.title} <span >${item.date}</span></h3>
 <img src="${item.url}" />
 <p>${item.explanation}</p></div>`).join('')

})
.date { font-size: xx-small; }
<div id="imageDiv"></div>

Older answer with one random image from a date range

const img = document.getElementById("apod");
let date, start = Date.parse('2021-01-01'), end = new Date();
end.setDate(end.getDate()-1);
const getDate = () => { 
  date = new Date(Math.floor(Math.random() * (end - start   1)   start)).toISOString().split('T')[0]; 
  return date
};

fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&start_date=${getDate()}&end_date=${date}`)
.then(response => response.json())
.then(data => {
  img.src = data[0].url
})
<img id="apod" />

  • Related