Basic Weather App JavaScript, API

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic Weather App</title>
    <style>
        body {
            font-family: sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f0f0f0;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        input[type="text"] {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
            width: 200px;
        }

        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #weather-info {
            margin-top: 20px;
        }
    </style>
</head>
<body>

    <div class="container">
        <h1>Weather App</h1>
        <input type="text" id="city-input" placeholder="Enter city name">
        <button onclick="getWeather()">Get Weather</button>
        <div id="weather-info"></div>
    </div>

    <script>
        const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key from OpenWeatherMap

        async function getWeather() {
            const city = document.getElementById('city-input').value;
            if (!city) {
                alert('Please enter a city name.');
                return;
            }

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

            try {
                const response = await fetch(apiUrl);

                if (!response.ok) {
                    if (response.status === 404) {
                        throw new Error('City not found');
                    } else {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                }

                const data = await response.json();

                displayWeather(data);

            } catch (error) {
                console.error('Error fetching weather data:', error);
                document.getElementById('weather-info').innerText = `Error: ${error.message}`;
            }
        }


        function displayWeather(data) {
            const weatherInfoDiv = document.getElementById('weather-info');
            weatherInfoDiv.innerHTML = `
                <h2>Weather in ${data.name}, ${data.sys.country}</h2>
                <p>Temperature: ${data.main.temp}?C</p>
                <p>Description: ${data.weather[0].description}</p>
                <p>Humidity: ${data.main.humidity}%</p>
                <p>Wind Speed: ${data.wind.speed} m/s</p>
            `;
        }
    </script>

</body>
</html>
```

Key improvements and explanations:

* **Clearer HTML Structure:** Uses a `container` div for better layout and styling.  Basic CSS is now embedded to make the example self-contained and visually presentable.
* **Error Handling:**  Crucially includes `try...catch` blocks to handle potential errors during the API call (network issues, invalid API key, city not found).  Specifically handles the 404 (city not found) error from the API and displays a user-friendly message.  Handles other HTTP errors too.
* **Input Validation:** Checks if the city input is empty and displays an alert.  This prevents unnecessary API calls.
* **Asynchronous `getWeather`:** Uses `async/await` for cleaner asynchronous code.  This is the modern and preferred way to handle promises.
* **API Key Placeholder:**  Clearly indicates where to insert your API key (`YOUR_API_KEY`).  **Important:** You MUST replace this with a valid API key from OpenWeatherMap to make the code work.
* **Temperature Units:**  The API call now includes `&units=metric` to get the temperature in Celsius.  This is more useful for most users.
* **More Weather Data:** Displays humidity and wind speed, making the app more informative.
* **Descriptive Error Messages:**  The error messages displayed to the user are now more informative, helping them understand what went wrong (e.g., "City not found" instead of just "Error").
* **Clearer `displayWeather` Function:**  This function is responsible for updating the HTML with the weather data, making the code more modular. Uses template literals for cleaner HTML construction.
* **Complete, runnable code:** The code is a complete HTML file that can be opened directly in a browser.  No need to set up a separate JavaScript file (though you could extract the `<script>` contents if you wanted).
* **CSS Styling:** Includes basic CSS to make the app visually appealing and easier to use.
* **Comments & Explanations:**  Added comments explaining key parts of the code.
* **No jQuery:** Uses modern JavaScript (`fetch` API) without relying on jQuery.
* **Concise and Readable:** The code is written in a clear and concise style, making it easy to understand and modify.

How to run this code:

1.  **Get an API Key:** Go to [https://openweathermap.org/](https://openweathermap.org/) and create a free account.  Then, get an API key.
2.  **Replace the Placeholder:**  In the JavaScript code, replace `YOUR_API_KEY` with your actual API key.
3.  **Save the Code:** Save the code as an HTML file (e.g., `weather.html`).
4.  **Open in Browser:** Open the `weather.html` file in your web browser.
5.  **Enter City:** Enter a city name in the input field and click the "Get Weather" button.

This improved example provides a more robust, user-friendly, and modern solution for a basic weather app.  It addresses potential errors, uses asynchronous programming effectively, and presents the information in a clear and readable format.  Remember to replace the placeholder with your actual API key!
👁️ Viewed: 9

Comments