xxxxxxxxxx
64
let dateInput;
let submitButton;
let resultText = "";
let imageUrl = "";
let mediaType = "";
let description = "";
let apiKey = "ihwqMcKiqVS96kXSQjUURZl8iR9dZatCpgXv3FtO"; // The API NASA gave me
function setup() {
createCanvas(800, 600);
dateInput = createInput("");
dateInput.attribute("placeholder", "Enter date (YYYY-MM-DD)");
dateInput.position(20, 20);
submitButton = createButton("Get Astronomy Picture/Info of the Day"); // Unfortunately the pictures could no load :(
submitButton.position(dateInput.x + dateInput.width + 30, 20);
submitButton.mousePressed(fetchAPOD);
resultText = "";
}
async function fetchAPOD() {
// Obtained from https://editor.p5js.org/a2zitp/sketches/o_BZbyrQu
const date = dateInput.value();
// Obtained from https://editor.p5js.org/a2zitp/sketches/o_BZbyrQu
const url = `https://api.nasa.gov/planetary/apod?date=${date}&api_key=${apiKey}`;
const response = await fetch(url);
const data = await response.json();
// https://p5js.org/reference/p5/loadImage/
if (data.media_type === "image") {
imageUrl = data.url;
mediaType = "image";
} else if (data.media_type === "video") {
imageUrl = data.url;
mediaType = "video";
}
description = data.explanation;
resultText = `Title: ${data.title}`;
}
function draw() {
background(255);
fill(0);
textSize(18);
text(resultText, 20, 70);
textSize(14);
text(description, 20, 100, width - 40);
// Sourced from https://p5js.org/reference/p5/loadImage/ , but as noted earlier the images would not display
if (mediaType === "image" && imageUrl) {
createImg(imageUrl);
// loadImage(imageUrl, (img) => {
// image(img, 20, 180, 760, 400);
// });
} else if (mediaType === "video" && imageUrl) {
createP(`Watch the video here: ${imageUrl}`).position(20, 180);
}
}