Create Coordinate-Based Weather Loading
Create Coordinate-Based Weather Loading
Task
Create fetchByCoordinates(lat, lon) so geolocation and unit switching can load a location without repeating city-name logic.
Open
Add the function after fetchWeather().
Implementation
async function fetchByCoordinates(lat, lon) {
requireKey();
showError("");
showLoader(true);
try {
const params = new URLSearchParams({ lat, lon, appid: API_KEY, units: state.unit });
const response = await fetch(`${API_BASE}/weather?${params}`);
if (!response.ok) throw new Error("Could not find weather for your location.");
const current = await response.json();
const forecastParams = new URLSearchParams({ lat, lon, appid: API_KEY, units: state.unit });
const forecastResponse = await fetch(`${API_BASE}/forecast?${forecastParams}`);
if (!forecastResponse.ok) throw new Error("Could not load the forecast.");
const forecast = await forecastResponse.json();
displayCurrent(current);
displayForecast(forecast);
$("updated").textContent = "Updated just now";
} catch (error) {
showError(error.message);
} finally {
showLoader(false);
}
}
The function is intentionally similar to the city flow because it needs the same two data sets. The key design choice is that both paths reuse displayCurrent() and displayForecast(), so the UI cannot drift into two different rendering implementations.
Test
If desired, call fetchByCoordinates() from DevTools with known coordinates. Confirm the returned location renders through the same current and forecast UI.
Expected result
The application has a reusable coordinate-based data path.
Checkpoint
Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.