14 - Weather Widget with Temperature and Description

Description

Develop a web application or widget that displays current weather information in a compact format:

  • Show the current temperature, including units (Celsius or Fahrenheit).

  • Provide a brief weather description (e.g., Sunny, Rainy, Clouds).

  • Optionally, include additional information like humidity, wind speed, or forecast icons.

  • Allow users to choose their preferred location or update automatically based on geolocation.

Algorithm

  1. Data Acquisition:

    • Use a weather API (e.g., OpenWeatherMap) to fetch weather data for a specific location.

    • Parse the API response to extract relevant information like temperature, description, and optional details.

  2. UI Components:

    • Render the current temperature prominently, formatted with appropriate units.

    • Display the weather description next to the temperature.

    • Optionally, include additional elements like humidity, wind speed, and weather icons.

  3. User Interaction:

    • Provide a location input field or button to allow manual location selection.

    • Implement geolocation support to automatically detect the user's location.

    • Refresh the weather data based on changes in location or user request.

Code

const apiKey = 'YOUR_API_KEY'; // Replace with your API key
const weatherUrl = (lat, lon) => `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`;

function WeatherWidget() {
  const [location, setLocation] = useState('');
  const [weatherData, setWeatherData] = useState(null);

  const fetchWeather = async (location) => {
    if (!location) return;
    const geocodedLocation = await geocodeLocation(location);
    const { lat, lon } = geocodedLocation;
    const response = await fetch(weatherUrl(lat, lon));
    const data = await response.json();
    setWeatherData(data);
  };

  useEffect(() => {
    navigator.geolocation.getCurrentPosition((position) => {
      const { latitude, longitude } = position.coords;
      fetchWeather(null, latitude, longitude);
    });
  }, []);

  if (!weatherData) return <p>Loading weather...</p>;

  const { main, weather } = weatherData;
  const temp = Math.round(main.temp - 273.15); // Convert kelvin to Celsius
  const description = weather[0].description;

  return (
    <div className="weather-widget">
      <p>{temp}°C</p>
      <p>{description}</p>
      {/* Optionally add humidity, wind speed, and icons */}
      <input
        type="text"
        placeholder="Enter city name"
        onChange={(e) => setLocation(e.target.value)}
        onBlur={() => fetchWeather(location)}
      />
    </div>
  );
}

// ... helper functions for geocoding and error handling

export default WeatherWidget;

Additional Notes

  • Consider using UI libraries like React Bootstrap or Material UI for better styling.

  • Implement responsive design for optimal rendering on different devices.

  • Integrate weather icons corresponding to the weather description.

  • Add options for choosing temperature units (Celsius/Fahrenheit).

Last updated