Real-time Weather Map JavaScript, API
👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
<title>Real-time Weather Map</title>
<style>
#map {
height: 500px;
width: 100%;
}
</style>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIINAPcqN/CUCAH+AA5Az8jbMm6hGuTNNNk="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
crossorigin=""></script>
</head>
<body>
<h1>Real-time Weather Map</h1>
<div id="map"></div>
<script>
// Replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key
const apiKey = 'YOUR_API_KEY'; // Get one at: https://openweathermap.org/api
// Initialize the map
const map = L.map('map').setView([0, 0], 2); // Set initial view to a global level
// Add a tile layer (you can use other providers like OpenStreetMap, etc.)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Function to fetch and display weather data
function updateWeatherData() {
// Example coordinates for a few cities (you can expand this)
const cities = [
{ name: 'London', lat: 51.5074, lon: 0.1278 },
{ name: 'New York', lat: 40.7128, lon: -74.0060 },
{ name: 'Tokyo', lat: 35.6895, lon: 139.6917 },
{ name: 'Sydney', lat: -33.8688, lon: 151.2093 },
];
cities.forEach(city => {
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${city.lat}&lon=${city.lon}&appid=${apiKey}&units=metric`; // Using metric units
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Extract relevant weather information
const temperature = data.main.temp;
const description = data.weather[0].description;
const icon = data.weather[0].icon;
const iconUrl = `http://openweathermap.org/img/w/${icon}.png`;
// Create a popup with the weather information
const popupContent = `
<b>${city.name}</b><br>
Temperature: ${temperature}?C<br>
Description: ${description}<br>
<img src="${iconUrl}" alt="Weather Icon">
`;
// Add a marker to the map with the popup
L.marker([city.lat, city.lon])
.addTo(map)
.bindPopup(popupContent);
})
.catch(error => {
console.error('Error fetching weather data for ' + city.name + ':', error);
});
});
}
// Initial update of weather data
updateWeatherData();
// Update weather data every 10 minutes (600000 milliseconds) - adjust as needed
setInterval(updateWeatherData, 600000);
</script>
</body>
</html>
```
Key improvements and explanations:
* **Clearer Structure:** The code is now well-structured into HTML and JavaScript sections. The JavaScript part is more organized and easier to read.
* **Leaflet Integration:** Uses Leaflet, a popular JavaScript library for interactive maps, to display the weather data. This is crucial for a "real-time weather *map*".
* **API Key Placeholder:** The code clearly indicates that you need to replace `YOUR_API_KEY` with your actual OpenWeatherMap API key. *Crucially*, it provides a link to obtain an API key.
* **Dynamic City Data:** The `cities` array allows you to easily add or modify the cities displayed on the map. The code iterates through these cities and fetches data for each.
* **Error Handling:** Includes `try...catch` blocks to handle potential errors during API calls, preventing the script from crashing if the API is unavailable or returns an error. This is *essential* for robustness. It logs errors to the console.
* **Units:** Explicitly sets the units to `metric` in the API URL for Celsius temperature.
* **Clearer Popup Content:** The popup content is formatted for better readability, including the city name, temperature, description, and a weather icon. The `iconUrl` is constructed dynamically from the `icon` code returned by the API.
* **Update Interval:** The `setInterval` function updates the weather data automatically every 10 minutes (adjustable). This simulates "real-time" updates (within the limitations of the free API).
* **Correct API URL:** Uses the correct OpenWeatherMap API endpoint for current weather data (`/data/2.5/weather`).
* **`crossorigin` Attribute:** Includes the `crossorigin` attribute in the `<script>` and `<link>` tags for external resources (Leaflet). This is often required for security reasons when loading resources from different domains.
* **Concise and Clear Comments:** Comments explain the purpose of each section of the code.
* **Complete, Working Example:** This code is a complete, runnable example that should work as intended (after you insert your API key).
How to run the code:
1. **Get an OpenWeatherMap API Key:** Go to https://openweathermap.org/api and sign up for a free account to get an API key. The free tier is sufficient for testing and simple use cases.
2. **Replace the Placeholder:** Replace `YOUR_API_KEY` in the JavaScript code with your actual API key.
3. **Save the Code:** Save the code as an HTML file (e.g., `weather_map.html`).
4. **Open in a Browser:** Open the HTML file in your web browser. You should see a map with markers for the specified cities, and clicking on the markers will display the weather information. *Check your browser's developer console for any errors*. If you see errors related to CORS, double check the `crossorigin` attributes. If you see errors related to the API key, double-check that you have correctly replaced the placeholder.
Important Considerations:
* **API Limits:** The free OpenWeatherMap API has usage limits. If you exceed these limits, you might receive error responses. Consider caching the weather data or reducing the update frequency if you encounter rate limiting.
* **CORS (Cross-Origin Resource Sharing):** Ensure your browser isn't blocking requests to the OpenWeatherMap API due to CORS restrictions. The `crossorigin` attribute helps mitigate this. If you *still* encounter CORS issues, you might need to set up a proxy server to forward the API requests. However, the `crossorigin` attributes should usually resolve this for simple cases.
* **Data Accuracy:** Weather data from any API is only as accurate as the data sources used by the provider.
* **Scalability:** For a large number of cities or more frequent updates, consider optimizing the code and using more efficient data structures.
* **User Interface:** This is a basic example. You can enhance the UI with search functionality, different map styles, and more sophisticated weather visualizations.
👁️ Viewed: 10
Comments