Build a weather app with JavaScript by integrating APIs and geolocation. Get hands-on experience fetching real-time weather data and displaying it to users.
You’ve spent sixteen days on syntax and logic. Today you point JavaScript at the real world and ask it what the weather’s doing.
We’re building a small weather app: type in a city, get back the temperature, humidity, and wind. Along the way you’ll call a live API, read a JSON response, and pull the user’s location from the browser. None of this is throwaway. Fetching remote data and putting it on the page is most of what front-end work actually is.
Table of Contents
- API Key Acquisition and Setup
- Fetching and Displaying Weather Data
- Geolocation and User Input Handling
- Enhancing User Experience: Styling and Responsiveness
- Adding Advanced Features
- Debugging and Optimization
- Conclusion
API Key Acquisition and Setup
Real weather data has to come from somewhere. We’ll use the OpenWeatherMap API, which serves current conditions and forecasts as JSON over a plain HTTP request.
1. Why Use a Weather API?
You don’t want to run your own weather station. An API hands you current conditions and forecasts, and you spend your time on the app instead of the meteorology. OpenWeatherMap is a common pick because the docs are clear and the free tier is plenty to learn on.
2. Registering and Obtaining an API Key
- Create an account: sign up at OpenWeatherMap.
- Choose a plan: the free tier covers this project.
- Retrieve your key: it’s under the “API keys” tab in your account. Heads up, a brand-new key can take a little while to go live, so if your first requests come back 401, give it some time before you assume the code is broken.
3. Integrating the API Key in Your Project
Here’s the honest part most tutorials skip. Any key you put in client-side JavaScript is public. It ships to the browser, so anyone can open the Network tab or view the page source and read it. There’s no hiding it in front-end code, no matter where you tuck the variable.
On your own machine, learning, that’s fine. The moment this goes anywhere real, move the key behind a small server-side endpoint you control: the browser calls your server, your server holds the key and calls OpenWeatherMap. That’s the only way the key stays yours. For now, drop it straight in so you can watch the app work:
/**
* Replace 'YOUR_API_KEY' with your OpenWeatherMap API key.
*/
const API_KEY = 'YOUR_API_KEY';Fetching and Displaying Weather Data
Key in hand, let’s ask for data and get it onto the page.
1. Crafting the API Request
We use fetch to hit the API. It returns a promise; response.json() reads the body and returns another promise, which is why there are two chained .then calls. Here’s a request for London:
/**
* Fetches weather data from the OpenWeatherMap API.
*
* @param {string} city - The city for which to fetch weather data.
* @returns {void}
*/
function fetchWeather(city) {
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`;
fetch(url)
.then(response => response.json())
.then(data => displayWeather(data));
}
Two things worth knowing about that URL. It’s http; use https in anything real so the request isn’t sent in the clear. And OpenWeatherMap has deprecated lookups by city name (the q= parameter): they still work, but they’re frozen, no more fixes or updates, and the docs now steer you toward their Geocoding API to turn a place name into latitude and longitude first. Fine for a demo. Worth knowing before you build on it.
2. Displaying Weather Information
Once the data’s back, pull out the pieces you care about and write them into the page:
/**
* Displays weather data on the webpage.
*
* @param {Object} data - The weather data from the API.
* @returns {void}
*/
function displayWeather(data) {
const temp = (data.main.temp - 273.15).toFixed(1); // Convert from Kelvin to Celsius
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
document.getElementById('temperature').textContent = `Temperature: ${temp}°C`;
document.getElementById('humidity').textContent = `Humidity: ${humidity}%`;
document.getElementById('wind-speed').textContent = `Wind Speed: ${windSpeed} m/s`;
}
That - 273.15 isn’t magic. OpenWeatherMap returns temperature in Kelvin by default, so you subtract to get Celsius. If you’d rather skip the arithmetic, add units=metric to the URL and it hands you Celsius directly (units=imperial gives you Fahrenheit).
Geolocation and User Input Handling
Making people type their city every time is friction. Let the browser offer their location, and let them search when they’d rather.
1. Obtaining User’s Geolocation
The Geolocation API reads latitude and longitude straight from the browser:
/**
* Fetches the user's current geolocation and retrieves weather data.
*
* @returns {void}
*/
navigator.geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords;
fetchWeatherByCoords(latitude, longitude);
});
Two rules the browser enforces here. Geolocation only works in a secure context, so HTTPS (localhost counts while you develop), and it always prompts the user for permission first. That means you can’t count on getting coordinates back. Give getCurrentPosition a second callback to handle the case where they decline or the lookup fails.
2. Customizing Search Functionality
Alongside location, let people search by city or zip. A field and a button:
<input type="text" id="location" placeholder="Enter city or zip" />
<button onclick="searchLocation()">Search</button>
And the handler that reads the input and reuses fetchWeather:
/**
* Fetches weather data based on user input.
*
* @returns {void}
*/
function searchLocation() {
const location = document.getElementById('location').value;
fetchWeather(location);
}Enhancing User Experience: Styling and Responsiveness
An app that only looks right on your laptop isn’t finished. Lay it out so it reads on a phone, keep the numbers big and legible, and make sure a failed request shows a message instead of a blank card. Plain CSS is enough here; you don’t need a framework for one panel of data.
Adding Advanced Features
Once the basics hold up, there’s room to grow:
- 5-day forecast: OpenWeatherMap’s 5-day / 3-hour forecast endpoint takes this beyond right now.
- Weather maps: layer in their map tiles for a visual read of conditions.
- Local time: show the searched location’s local time so the numbers have context.
Debugging and Optimization
Live in your browser’s dev tools while you build this. The Network tab shows you exactly what the API sent back, which is where most weather-app bugs actually hide. And don’t hammer the API: cache a result for a few minutes instead of re-fetching on every keystroke. The free tier has rate limits, and you’ll hit them faster than you’d think.
Conclusion
That’s a working weather app: a live API, a JSON response rendered to the page, the browser’s location, and user input, all wired together. Small surface, but it’s the shape of nearly every data-driven front end you’ll build.
The one thing to carry forward past the code: that API key is public the second it lands in the browser. A demo can live with that; a real app puts the key on a server you control. Everything else here you can extend freely, a forecast, maps, whatever you want.
What’s Next?
Day 18 moves from apps to ideas. We’ll get into Functional Programming in JavaScript: pure functions, immutability, and composing small pieces into clean, maintainable code. See you there.


