-
Obtenez des données météorologiques en temps réel avec Leaflet.js et Open-Meteo
- 19 août 2024
// Initialize the map
var map = L.map('map').setView([0, 0], 2);
// Add OpenStreetMap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Función para obtener datos meteorológicos de Open-Meteo
async function getWeather(lat, lon) {
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t_weather=true`;
const response = await fetch(url);
const data = await response.json();
return data.current_weather;
}
// Función para agregar marcadores de clima al mapa
async function addWeatherMarker(lat, lon) {
const weather = await getWeather(lat, lon);
const marker = L.marker([lat, lon]).addTo(map);
marker.bindPopup(`
<b>Ubication</b><br>
weathercode: ${weather.weathercode}<br>
temperature: ${weather.temperature} °C<br>
windspeed: ${weather.windspeed} km/h
`).openPopup();
}
map.on('click', function(e) {
addWeatherMarker(e.latlng.lat, e.latlng.lng);
});