File size: 12,303 Bytes
08c2b86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb1a2a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vientos de Lima | Wind Whisperer</title>
    <link rel="icon" type="image/x-icon" href="https://static.photos/blue/200x200/42">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/feather-icons"></script>
    <script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css"/>
    <script src="https://cdn.jsdelivr.net/npm/chroma-js@2.4.2/chroma.min.js"></script>
    <style>
        #map {
            height: 100vh;
            width: 100%;
            position: relative;
        }
        .wind-arrow {
            position: absolute;
            transform-origin: center;
            stroke-linecap: round;
        }
        .legend {
            background: rgba(255, 255, 255, 0.9);
            padding: 1rem;
            border-radius: 0.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .legend-gradient {
            height: 20px;
            width: 100%;
            border-radius: 4px;
            margin: 10px 0;
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <div class="flex flex-col h-screen">
        <header class="bg-gradient-to-r from-blue-500 to-cyan-400 text-white p-4 shadow-md">
            <div class="container mx-auto flex justify-between items-center">
                <h1 class="text-2xl font-bold flex items-center">
                    <i data-feather="wind" class="mr-2"></i> Lima Wind Whisperer
                </h1>
                <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                        <label for="unit-select" class="mr-2 text-sm font-medium">Unidad:</label>
                        <select id="unit-select" class="bg-white/20 border border-white/30 rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-white">
                            <option value="kmh">km/h</option>
                            <option value="ms">m/s</option>
                            <option value="knots">nudos</option>
                        </select>
                    </div>
                    <button id="refresh-btn" class="flex items-center bg-white/20 hover:bg-white/30 px-3 py-1 rounded transition">
                        <i data-feather="refresh-cw" class="mr-1" width="16"></i>
                        <span class="text-sm">Actualizar</span>
                    </button>
                </div>
            </div>
        </header>

        <div id="map"></div>

        <div id="legend" class="absolute bottom-4 right-4 z-[1000] legend">
            <h3 class="font-bold text-gray-800 mb-2">Velocidad del viento</h3>
            <div id="legend-gradient" class="legend-gradient"></div>
            <div class="flex justify-between text-xs text-gray-600">
                <span>0</span>
                <span>20</span>
                <span>40 km/h</span>
            </div>
        </div>

        <div id="tooltip" class="absolute bg-white p-3 rounded shadow-lg z-[1000] hidden">
            <div class="flex items-center mb-1">
                <i data-feather="map-pin" class="text-blue-500 mr-2" width="16"></i>
                <span id="location" class="font-medium"></span>
            </div>
            <div class="grid grid-cols-2 gap-2 text-sm">
                <div class="flex items-center">
                    <i data-feather="compass" class="text-gray-500 mr-2" width="14"></i>
                    <span id="direction"></span>
                </div>
                <div class="flex items-center">
                    <i data-feather="wind" class="text-gray-500 mr-2" width="14"></i>
                    <span id="speed"></span>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Configuración inicial
        const config = {
            center: [-12.0464, -77.0428], // Lima
            zoom: 11,
            minZoom: 8,
            maxZoom: 18,
            windDataUrl: 'https://api.open-meteo.com/v1/gfs?latitude=-12.0464&longitude=-77.0428&hourly=windspeed_10m,winddirection_10m',
            updateInterval: 600000 // 10 minutos
        };

        // Inicializar mapa
        const map = L.map('map', {
            center: config.center,
            zoom: config.zoom,
            minZoom: config.minZoom,
            maxZoom: config.maxZoom
        });

        // Añadir capa base
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // Escala de colores para la velocidad del viento
        const colorScale = chroma.scale(['#4cc9f0', '#4361ee', '#3a0ca3', '#7209b7', '#f72585']).domain([0, 40]);

        // Actualizar gradiente de leyenda
        function updateLegendGradient() {
            const gradient = document.getElementById('legend-gradient');
            gradient.style.background = `linear-gradient(to right, ${colorScale(0).hex()}, ${colorScale(10).hex()}, ${colorScale(20).hex()}, ${colorScale(30).hex()}, ${colorScale(40).hex()})`;
        }

        // Convertir dirección meteorológica a cardinal
        function degreesToCardinal(degrees) {
            const cardinals = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
            const index = Math.round((degrees % 360) / 22.5);
            return cardinals[(index % 16)];
        }

        // Dibujar flecha de viento
        function drawWindArrow(latlng, speed, direction, unit = 'kmh') {
            // Normalizar velocidad según unidad
            let displaySpeed;
            let displayUnit;
            
            switch(unit) {
                case 'ms':
                    displaySpeed = speed / 3.6;
                    displayUnit = 'm/s';
                    break;
                case 'knots':
                    displaySpeed = speed / 1.852;
                    displayUnit = 'kt';
                    break;
                default:
                    displaySpeed = speed;
                    displayUnit = 'km/h';
            }
            
            // Convertir dirección meteorológica (de dónde viene) a dirección gráfica (hacia dónde va)
            const graphicDirection = (direction + 180) % 360;
            
            // Calcular tamaño proporcional a la velocidad (con límites)
            const minSize = 10;
            const maxSize = 30;
            const size = Math.min(maxSize, Math.max(minSize, speed / 2));
            
            // Crear elemento SVG para la flecha
            const arrow = document.createElementNS("http://www.w3.org/2000/svg", "svg");
            arrow.setAttribute("width", size * 2);
            arrow.setAttribute("height", size * 2);
            arrow.setAttribute("viewBox", "0 0 24 24");
            arrow.className = "wind-arrow";
            arrow.setAttribute("data-speed", speed);
            arrow.setAttribute("data-direction", direction);
            arrow.setAttribute("data-lat", latlng.lat);
            arrow.setAttribute("data-lng", latlng.lng);
            arrow.setAttribute("data-unit", unit);
            
            // Definir la flecha como un path SVG
            const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
            path.setAttribute("d", "M12 2L4 12L8 12L8 22L16 22L16 12L20 12L12 2Z");
            path.setAttribute("fill", colorScale(speed).hex());
            path.setAttribute("stroke", "#fff");
            path.setAttribute("stroke-width", "0.5");
            
            arrow.appendChild(path);
            arrow.style.transform = `rotate(${graphicDirection}deg)`;
            
            // Convertir a capa Leaflet
            const icon = L.divIcon({
                html: arrow.outerHTML,
                className: '',
                iconSize: [size, size]
            });
            
            const marker = L.marker(latlng, {
                icon: icon,
                interactive: true
            }).addTo(map);
            
            // Eventos para tooltip
            marker.on('mouseover', function(e) {
                const tooltip = document.getElementById('tooltip');
                tooltip.style.left = `${e.originalEvent.clientX + 10}px`;
                tooltip.style.top = `${e.originalEvent.clientY + 10}px`;
                tooltip.classList.remove('hidden');
                
                document.getElementById('location').textContent = `${latlng.lat.toFixed(4)}, ${latlng.lng.toFixed(4)}`;
                document.getElementById('direction').textContent = `${direction}° ${degreesToCardinal(direction)}`;
                document.getElementById('speed').textContent = `${displaySpeed.toFixed(1)} ${displayUnit}`;
            });
            
            marker.on('mouseout', function() {
                document.getElementById('tooltip').classList.add('hidden');
            });
            
            return marker;
        }

        // Generar datos de viento simulados (en una aplicación real, esto vendría de una API)
        function generateWindData() {
            const data = [];
            const gridSize = 0.1;
            
            for(let lat = -12.2; lat <= -11.9; lat += gridSize) {
                for(let lng = -77.2; lng <= -76.8; lng += gridSize) {
                    // Simular variaciones de velocidad y dirección
                    const baseSpeed = 5 + Math.random() * 20;
                    const speed = baseSpeed + Math.sin(lat * 10) * 5 + Math.cos(lng * 10) * 5;
                    const direction = (270 + (lat + 12) * 100 + (lng + 77) * 50) % 360;
                    
                    data.push({
                        latlng: [lat, lng],
                        speed: Math.max(0, speed),
                        direction: direction
                    });
                }
            }
            
            return data;
        }

        // Actualizar visualización con nuevos datos
        function updateWindData(unit = 'kmh') {
            // Limpiar marcadores existentes
            map.eachLayer(layer => {
                if (layer instanceof L.Marker) {
                    map.removeLayer(layer);
                }
            });
            
            // Generar o cargar datos
            const windData = generateWindData();
            
            // Dibujar flechas según el nivel de zoom
            const currentZoom = map.getZoom();
            let sampleRate = 1;
            
            if (currentZoom < 10) sampleRate = 4;
            else if (currentZoom < 12) sampleRate = 2;
            
            for(let i = 0; i < windData.length; i += sampleRate) {
                const point = windData[i];
                drawWindArrow(
                    L.latLng(point.latlng[0], point.latlng[1]),
                    point.speed,
                    point.direction,
                    unit
                );
            }
        }

        // Manejar cambios en la unidad
        document.getElementById('unit-select').addEventListener('change', function() {
            updateWindData(this.value);
        });

        // Manejar actualización manual
        document.getElementById('refresh-btn').addEventListener('click', function() {
            updateWindData(document.getElementById('unit-select').value);
        });

        // Manejar cambios de zoom
        map.on('zoomend', function() {
            updateWindData(document.getElementById('unit-select').value);
        });

        // Actualizar automáticamente
        function startAutoRefresh() {
            updateWindData();
            updateLegendGradient();
            setInterval(() => {
                updateWindData(document.getElementById('unit-select').value);
            }, config.updateInterval);
        }

        // Inicializar
        document.addEventListener('DOMContentLoaded', function() {
            feather.replace();
            startAutoRefresh();
        });
    </script>
</body>
</html>