Sketch 2026-02-08 12:55

This is not a p5.js creative coding sketch—it is a web application that fetches real-time weather data from OpenWeatherMap API and displays agricultural advisory information on an HTML page. The sketch.js file contains only a single async function that retrieves weather data, and the project is primarily HTML/CSS/JavaScript for agricultural decision support, not visual art or interactive graphics created with p5.js.

🧪 Try This!

Experiment with the code by making these changes:

  1. Fetch weather for a different city — Changing the city string will make the API request weather data for that location instead—watch the displayed temperature, humidity, and wind speed update to reflect the new city
  2. Display temperature in Fahrenheit — The units=metric parameter in the URL requests Celsius; changing it to units=imperial will switch the API response to Fahrenheit, and the displayed temperature will be much larger
  3. Round the temperature to whole numbers — The API returns temperature as a decimal—wrapping it in Math.round() removes the fractional part, making the display cleaner
Prefer the full editor? Open it there →

📖 About This Sketch

This project is an agricultural advisory web application, not a p5.js creative coding sketch. The sketch.js file contains a single async function called getWeather() that fetches real-time temperature, humidity, and wind speed data from the OpenWeatherMap API for Dhaka, Bangladesh. While the HTML loads p5.js as a library, it is not actually used in this code—the project is a traditional web application built with HTML, CSS, and vanilla JavaScript.

If you are looking to learn p5.js visual programming, animation, or interactive graphics, this is not the right sketch. However, if you want to understand how to fetch data from external APIs, handle asynchronous JavaScript with async/await, parse JSON responses, and update the DOM with real-time information, this code demonstrates those web development fundamentals clearly.

⚙️ How It Works

  1. When the getWeather() function is called, it defines the city name ('Dhaka') and an API key from OpenWeatherMap, then constructs a URL with those parameters to request current weather data in metric units (Celsius)
  2. The function uses fetch() to send an HTTP GET request to the OpenWeatherMap API asynchronously—the await keyword pauses execution until the API responds
  3. Once the response arrives, .json() parses it into a JavaScript object containing weather fields like temperature, humidity, and wind speed
  4. Three lines of code then grab HTML elements by their IDs and insert the weather data as text, combining Bengali labels with the numeric values
  5. If any error occurs during the fetch or parsing, a catch block logs the error to the browser console instead of crashing the page

🎓 Concepts You'll Learn

Asynchronous programming (async/await)Fetch API and HTTP requestsJSON parsingError handling (try/catch)DOM manipulationTemplate literals

📝 Code Breakdown

getWeather()

This function teaches the modern JavaScript async/await pattern for handling asynchronous operations like API calls. The async keyword makes the function always return a Promise, and await pauses execution until that Promise resolves. This is much cleaner than old-style .then() callbacks. The try/catch pattern is essential because network requests can fail—catching errors prevents your entire app from crashing when the API is unavailable.

🔬 This line combines a Bengali label with a number using string concatenation. What happens if you change the label from 'তাপমাত্রা: ' to 'Temperature: ' or add extra text?

        document.getElementById("temp").innerText =
        "তাপমাত্রা: " + data.main.temp + "°C";

🔬 These two lines are the heart of async/await. What happens if you remove the await keyword from one of them? (Hint: you will get a Promise object instead of the actual data—try it!)

        let response = await fetch(url);
        let data = await response.json();
async function getWeather(){

    let city = "Dhaka";
    let apiKey = "786c9b9d5cd13cc8780fc9c089b9d014";

    let url =
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

    try{
        let response = await fetch(url);
        let data = await response.json();

        document.getElementById("temp").innerText =
        "তাপমাত্রা: " + data.main.temp + "°C";

        document.getElementById("humidity").innerText =
        "আর্দ্রতা: " + data.main.humidity + "%";

        document.getElementById("wind").innerText =
        "বাতাসের গতি: " + data.wind.speed + " m/s";

    }catch(error){
        console.log("Weather Error:", error);
    }
}
Line-by-line explanation (13 lines)

🔧 Subcomponents:

calculation API URL Construction let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

Builds the API endpoint URL using template literals to inject the city and API key parameters

calculation Asynchronous Fetch Request let response = await fetch(url);

Sends an HTTP GET request and pauses execution until the server responds

calculation JSON Parsing let data = await response.json();

Converts the response from text into a usable JavaScript object

calculation Temperature DOM Update document.getElementById("temp").innerText = "তাপমাত্রা: " + data.main.temp + "°C";

Finds the HTML element with id='temp' and inserts the temperature value as text

calculation Humidity DOM Update document.getElementById("humidity").innerText = "আর্দ্রতা: " + data.main.humidity + "%";

Finds the HTML element with id='humidity' and inserts the humidity percentage

calculation Wind Speed DOM Update document.getElementById("wind").innerText = "বাতাসের গতি: " + data.wind.speed + " m/s";

Finds the HTML element with id='wind' and inserts the wind speed value

conditional Error Handling catch(error){ console.log("Weather Error:", error); }

Catches any errors during the fetch or JSON parsing and logs them to the console instead of crashing

async function getWeather(){
Declares an asynchronous function—async allows the use of await inside, letting the code pause and wait for API responses
let city = "Dhaka";
Stores the city name as a string variable that will be inserted into the API URL
let apiKey = "786c9b9d5cd13cc8780fc9c089b9d014";
Stores your OpenWeatherMap API key—this authenticates your request to their server
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
Uses a template literal (backticks) to build the full API URL, injecting city and apiKey variables into the query parameters
try{
Starts a try-catch block—any code inside try will be monitored, and if an error occurs, it jumps to catch
let response = await fetch(url);
Sends an HTTP request to the API URL and waits for the server to respond; await pauses here until data arrives
let data = await response.json();
Converts the response body (which arrives as text) into a JavaScript object by parsing the JSON; await waits for this conversion
document.getElementById("temp").innerText = "তাপমাত্রা: " + data.main.temp + "°C";
Finds the HTML element with id='temp', then sets its text content to a Bengali label plus the temperature value from the API data
document.getElementById("humidity").innerText = "আর্দ্রতা: " + data.main.humidity + "%";
Finds the element with id='humidity' and sets its text to a Bengali label plus the humidity percentage from the API
document.getElementById("wind").innerText = "বাতাসের গতি: " + data.wind.speed + " m/s";
Finds the element with id='wind' and sets its text to a Bengali label plus the wind speed value
}catch(error){
If any error occurred in the try block above, execution jumps here
console.log("Weather Error:", error);
Logs the error message to the browser console so developers can debug without the page crashing
}
Closes the catch block

📦 Key Variables

city string

Stores the name of the city for which weather data will be fetched from the API

let city = "Dhaka";
apiKey string

Stores the OpenWeatherMap API key needed to authenticate API requests

let apiKey = "786c9b9d5cd13cc8780fc9c089b9d014";
url string

Stores the complete API endpoint URL with city, API key, and unit parameters

let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
response object

Stores the HTTP response object from the fetch request, which contains status, headers, and body data

let response = await fetch(url);
data object

Stores the parsed JSON object containing weather information like temperature, humidity, and wind speed

let data = await response.json();
error object

Stores any error object that occurs during the fetch or JSON parsing, providing details about what went wrong

catch(error){ console.log("Weather Error:", error); }

🔧 Potential Improvements (5)

Here are some ways this code could be enhanced:

BUG sketch.js - getWeather() function

The API key is hardcoded in the source code. This is a security risk because anyone who reads the code can see and reuse your key, potentially causing your quota to be exceeded or allowing misuse.

💡 Store the API key in an environment variable or server-side configuration file, and fetch it securely from a backend endpoint instead of embedding it in client-side JavaScript.

BUG index.html - DOM references

The sketch.js file references HTML elements with IDs 'temp', 'humidity', and 'wind', but the index.html shows only static placeholder text without those IDs. The API data will have nowhere to display if this function is called.

💡 Add id attributes to the paragraphs in the HTML: <p id='temp'>তাপমাত্রা: ২৮°C</p>, <p id='humidity'>আর্দ্রতা: ৭০%</p>, and <p id='wind'>বাতাসের গতি: ৮ km/h</p>

FEATURE sketch.js - getWeather() function

The function has no way to be triggered. It is defined but never called, so the weather data will never be fetched.

💡 Add getWeather() call in a script tag in the HTML body after the page loads, or attach it to a button click: <button onclick='getWeather()'>Refresh Weather</button>

PERFORMANCE sketch.js - getWeather() function

There is no error feedback to the user—errors are only logged to the developer console, so farmers using this app will not know why weather data failed to load.

💡 Display user-friendly error messages in the UI instead of only logging to console: document.getElementById('temp').innerText = 'আবহাওয়া লোড ব্যর্থ। ইন্টারনেট সংযোগ পরীক্ষা করুন।'

STYLE index.html - head

The HTML loads p5.js library (p5.min.js) but it is never used anywhere in the project—this is unnecessary bloat that slows page load time.

💡 Remove the line <script src='https://cdn.jsdelivr.net/npm/p5@1.11.3/lib/p5.min.js'></script> from the head since this is a traditional web app, not a p5.js sketch.

🔄 Code Flow

Code flow showing getweather

💡 Click on function names in the diagram to jump to their code

graph TD start[Start] --> setup[setup] setup --> draw[draw loop] draw --> getweather[getweather] getweather --> urlconstruction[url-construction] urlconstruction --> fetchrequest[fetch-request] fetchrequest --> jsonparsing[json-parsing] jsonparsing --> domupdatetemp[dom-update-temp] jsonparsing --> domupdatehumidity[dom-update-humidity] jsonparsing --> domupdatewind[dom-update-wind] fetchrequest --> errorhandling[error-handling] errorhandling --> draw domupdatetemp --> draw domupdatehumidity --> draw domupdatewind --> draw click setup href "#fn-setup" click draw href "#fn-draw" click getweather href "#fn-getweather" click urlconstruction href "#sub-url-construction" click fetchrequest href "#sub-fetch-request" click jsonparsing href "#sub-json-parsing" click domupdatetemp href "#sub-dom-update-temp" click domupdatehumidity href "#sub-dom-update-humidity" click domupdatewind href "#sub-dom-update-wind" click errorhandling href "#sub-error-handling"

❓ Frequently Asked Questions

What visual elements can users expect to see in the Sketch 2026-02-08 12:55?

The sketch displays current weather information for Dhaka, including temperature, humidity, and wind speed, presented in Bengali.

Is there any interaction feature available in this weather sketch?

The sketch does not feature interactive elements; it automatically fetches and displays weather data without user input.

What creative coding concepts are showcased in this p5.js sketch?

The sketch demonstrates the use of asynchronous programming to fetch real-time weather data from an API and dynamically update the webpage content.

Preview

Sketch 2026-02-08 12:55 - p5.js creative coding sketch preview
Sketch Preview
Code flow diagram showing the structure of Sketch 2026-02-08 12:55 - Code flow showing getweather
Code Flow Diagram