Building a Weather App Using JavaScript and the OpenWeatherMap API
Have you thought about creating a weather app that makes it simple for consumers to access the most recent forecasts? Even if it sounds challenging, you can make a user-friendly weather app using JavaScript and the OpenWeatherMap API.
In this lesson, I'll walk you through the process. When you're done, you can access a helpful weather app that provides real-time weather forecasts.
Prerequisites:
Before we get started, let's make sure you have everything you need:
Basic JavaScript Skills:
You should be familiar with the basics of JavaScript, like variables, functions, and simple coding concepts.
Code Editor:
You will need a code editor to create and maintain the code for your app. You may make use of programs like Notepad+ or Visual Studio Code.
OpenWeatherMap API Key:
Obtain a unique key that enables your application to access weather information from OpenWeatherMap. It functions as a sort of unique app password.
Web Browser:
To test your app as you go, make sure you have a contemporary web browser like Chrome or Firefox.
Table of Contents
Setting up the project
Fetching Weather Data
Sending API Request
Displaying Weather Information
Temperature Conversion
User Interaction
Styling and responsiveness guidelines
Conclusion
Setting Up the Project
Make the foundation of your app's structure in your HTML file. To contain the content of the app, use a 'div' element with the class 'app'. Add a 'form' element with the class 'form' within, along with an 'input' element with the class 'search' to receive user input. Include a 'main' element with the class 'main' to display the weather data.
<div class="app">
<form action="#" class="form">
<input
type="text"
class="search"
placeholder="Search By Location"
autocomplete="off"
/>
</form>
<main class="main"></main>
</div>
Linking CSS:
Link your HTML to a CSS file to customize your application. The following line, pointing to the path of your CSS file, should be included in the 'head' section of your HTML.
<link rel="stylesheet" type="text/css" href="/styles.css">
Linking JavaScript:
Next, add functionality by linking your HTML to a JavaScript file. Before the 'body' tag closes, add the line that connects to your JavaScript code.
<script src="/script.js"></script>
JavaScript Powerhouse
Let's now apply JavaScript skills to breathe life into our app. Add the following code below to your JavaScript file (such as "script.js"):
const main = document.querySelector(".main");
const form = document.querySelector(".form");
const search = document.querySelector(".search");
We've used JavaScript's features to capture components from our HTML structure. Class selectors and the document.The querySelector function method, which is a part of the DOM API, provides us the ability to control and interact with particular areas of our program.
Fetching Weather Data
Obtaining weather data is a vital step in the process of providing real-time information to your weather app.
One of the crucial aspects of our weather app is the capability to obtain weather data from the OpenWeatherMap API. We use this information to provide customers with the most recent weather information for the location they've selected.
To begin, we've established a crucial connection between our app and the OpenWeatherMap API. The API acts as a data source, providing us with valuable weather insights.
API URL Construction:
To obtain your API key, follow these steps:
Visit the OpenWeatherMap website: openweathermap.org.
Sign up for a free account or log in if you already have one.
Once logged in, navigate to the API Keys section.
Click on the {API key}
Once you have your API key, you can integrate it into your url
function like this:
const apiKey = "YOUR_API_KEY_HERE";
Implementing the url Function:
The 'url' function is essential to the given code. It creates a "URL" that refers to the OpenWeatherMap API using the "city" argument. The 'city' field and your apiKey are included in the URL. This URL will be used to get the chosen city's weather data via API calls.
const url = function(city) {
return https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey};
}
Making / Sending the API Request
Once our URL is prepared, we enter the world of asynchronous function. It is the kind of function that enables the primary execution thread to carry on while allowing the main thread of execution to continue running.
async function getWeatherLocation(city) {
const resp = await fetch(url(city), {
mode: "cors"
});
The 'getWeatherLocation' method makes use of the fetch function to make a request to the OpenWeatherMap API. A contemporary method of sending network requests in JavaScript is to use the fetch function. We await the response for further processing.
The Cross-Origin Resource Sharing mode is indicated by the mode: "cors"
. Web browsers use CORS, a security feature, to limit how resources from one origin (domain) may be requested and used by web pages from another origin. Cross-origin requests have the potential to provide security issues, which are avoided by using this method.
Parsing the API Response
As the API provides us with a variety of information in JSON format in response to our request. The following action is to carefully extract and understand this data. mode: "cors"
});
const respData = await resp.json()
addWeatherToPage(respData);
}}
The "await" keyword is used to stop the code from running until the promise given by the "resp.json()
" function is fulfilled. This data, now represented by the'respData' variable, has useful weather data that we can explore.
Displaying Weather Information
Once the weather data is fetched, the addWeatherToPage function comes into play:
Temperature Conversion:
The temperature is changed from Kelvin to Celsius using the Ktoc function. It deducts 273.15 from the Kelvin value to get a temperature that is easier to understand.
function Ktoc(K) {
return Math.floor(K - 273.15);}
Updating the Page:
The created weather element is then added to the main section of the HTML. This process involves clearing any existing content within the main element and appending the new weather information.
function addWeatherToPage(data) {
const weather = document.createElement('div');
weather.classList.add('weather');
const temp = Ktoc(data.main.temp);
weather.innerHTML = `
<div class=box>
<img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png"/>
<h2>${temp} degree Celsius</h2>
<img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png"/>
</div>
<small>${data.weather[0].main}</small>
`;
main.innerHTML = "";
main.appendChild(weather);
}
Creating Dynamic Elements:
Inside the addWeatherToPage function, we create an HTML div
element to house our weather details. We populate this element with the temperature, weather icon, and weather condition. Additionally, we clear the app's main content (main.innerHTML = "";)
before appending the newly created weather
div.
main.innerHTML = "";
main.appendChild(weather);
}
User Interaction
The final part of the code deals with user interaction:
Form Submission:
The form element listens for a submission event (submit button click). When the form is submitted, the provided event listener captures the user's input (city name) from the search input field.
form.addEventListener('submit', (e) => {
e.preventDefault();
const city = search.value;
if(city) {
getWeatherLocation(city);}});
API Request and Display:
The getWeatherLocation method is invoked if a valid city name is given, starting the API request and displaying weather information processes.
Understanding and implementing these procedures will enable you to retrieve weather information from the OpenWeatherMap API and show it on your app's user interface, providing users with a useful and informative weather app.
Custom Styling and Responsiveness
It's time to add your distinctive flair to your weather app now that the basic structure and necessary features have been established. You have the creative flexibility to make your app adaptable to various screen sizes and style it in a way that aligns with your vision.
Express Your Style:
You are in control of how your weather app looks and feels. To develop a design that speaks to you, feel free to play around with fonts, colors, and layout. Let your creativity lead you in making your decisions, whether you want a simple, vivid, or exquisite style.
Responsive Design:
Think about the many platforms, from PCs to cellphones, that your consumers could utilize to access your app. Concentrate on responsiveness to provide a seamless experience for everyone.
Media Queries: To change your app's layout and design dependent on screen sizes, use @media queries in your CSS. This makes sure your software works smoothly and looks fantastic across a variety of devices.
Flexible Layouts: When sizing elements, use flexible units like percentages and viewport units (vw, vh). As a result, your program can adapt organically to various screen sizes.
Mobile-First Approach: Before improving the design for larger screens, start designing for smaller ones. This strategy guarantees that responsiveness has a solid foundation.
Test Across Devices: Test your app often on various platforms and browsers to find any layout or usability problems. Make necessary changes.
Remember, the Possibilities are Endless:
You may choose between a fun, colorful UI and a clean, contemporary style. The capacity to create distinctive user experiences is where web development's genuine beauty resides. Don't be afraid to look online for design inspiration and tools to help you get creative.
You'll be well on your way to developing a weather app that not only offers useful information but also satisfies users with its aesthetic appeal and usefulness if you embrace bespoke style and place a high priority on responsiveness. Happy coding and designing!
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
margin: 0 auto;
background: lightcyan;
display: flex;
align-items: center;
justify-content: center;
font-size: 1rem;
margin-top: 200px;
min-width: 400px;
}
.app {
display: flex;
align-items: center;
flex-direction: column;
width: 90%;
background-color: rgb(161, 210, 240);
padding: 50px;
border-radius: 5%;
}
input {
margin-bottom: 50px;
padding: 1rem;
border-radius: 25px;
border: none;
background-color: #fff;
font-family: inherit;
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
font-size: 1.2rem;
}
input:focus {
outline: none;
}
.weather {
text-align: center;
}
.weather .box {
margin-bottom: 30px;
display: flex;
align-items: center;
justify-content: space-around;
font-size: 1rem;
}
.weather .box .h2 {
font-size: 1rem;
}
.weather img {
transform: scale(1);
}
.weather small {
color: white;
background: black;
padding: 10px;
border-radius: 15px;
font-size: 1rem;
}
@media (min-width: 500px) {
.app {
width: 60%;
}
}
@media (min-width: 900px) {
.app {
width: 40%;
}
}
Conclusion
You have learned a lot about data retrieval, modification, and user interaction over your trip of creating a weather app using JavaScript and the OpenWeatherMap API. You have developed a useful weather app that educates and engages users by fusing technical expertise with imaginative design.
Keep in mind that this is only the beginning. There are countless prospects for improvement and additional investigation in the field of web development. Continue to explore, learn, and hone your abilities as you go along your coding path. Your weather app is proof of your potential, and there are countless opportunities in front of you.
Congratulations on creating your own weather app! Have fun coding with Awwal.