File size: 39,663 Bytes
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
cb4eb94
 
 
 
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
 
ac09981
 
 
cb4eb94
ac09981
 
 
 
cb4eb94
 
ac09981
 
cb4eb94
ac09981
cb4eb94
ac09981
 
cb4eb94
 
 
ac09981
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
cb4eb94
 
 
 
 
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4eb94
ac09981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GeoFoto - Fotografía a KML</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-out forwards;
        }
        
        #preview {
            transform: scaleX(-1); /* Espejo para selfie */
        }
        
        .watermark {
            text-shadow: 1px 1px 2px black, -1px -1px 2px black;
        }
        
        #map {
            height: 300px;
            width: 100%;
            border-radius: 0.5rem;
        }
        
        .leaflet-container {
            background: #1e293b;
        }
        
        .custom-marker {
            background: transparent;
            border: none;
        }
        
        .banner-container {
            width: 100%;
            overflow: hidden;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .banner-img {
            width: 100%;
            height: auto;
            display: block;
        }
        
        body {
            background-image: url('https://huggingface.co./datasets/ignaciomdr/fondos/resolve/main/HD%20wallpaper_%20vertical%2C%20landscape%2C%20science%2C%20nature%2C%20water%2C%20no%20people%2C%20red.jpeg');
            background-size: cover;
            background-attachment: fixed;
            background-position: center;
        }
        
        .bg-semi-transparent {
            background-color: rgba(15, 23, 42, 0.85);
        }
    </style>
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
</head>
<body class="text-slate-100 min-h-screen font-sans">
    <div class="container mx-auto px-4 py-8 max-w-3xl bg-semi-transparent rounded-xl">
        <!-- Header -->
        <header class="mb-4 fade-in">
            <div class="banner-container">
                <img src="https://cdn-uploads.huggingface.co/production/uploads/noauth/7vTxYaZUq3T2toaTItUKz.webp" alt="GeoFoto Banner" class="banner-img">
            </div>
            <div class="flex justify-between items-center">
                <div>
                    <p class="text-slate-400">Fotografía a KML</p>
                </div>
                <div class="flex items-center space-x-2">
                    <div id="gps-status" class="flex items-center text-sm">
                        <div class="w-3 h-3 rounded-full bg-rose-500 mr-2"></div>
                        <span>GPS: Desconectado</span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <div class="grid grid-cols-1 gap-8">
            <!-- User Input Section -->
            <div class="bg-slate-800 rounded-xl p-6 shadow-xl fade-in">
                <h2 class="text-xl font-semibold mb-4 flex items-center">
                    <i class="fas fa-user-circle text-blue-400 mr-2"></i>
                    Registrado por
                </h2>
                <div class="space-y-4">
                    <div>
                        <label for="operator-name" class="block text-sm font-medium text-slate-300 mb-1">Nombre</label>
                        <input type="text" id="operator-name" class="w-full bg-slate-700 border border-slate-600 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 transition" placeholder="Ej: Juan Pérez" required>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-slate-300 mb-1">Área</label>
                        <div class="grid grid-cols-3 gap-2">
                            <button id="ambiente-btn" class="area-btn px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg flex items-center justify-center transition">
                                <i class="fas fa-leaf mr-2"></i> Medio Ambiente
                            </button>
                            <button id="sso-btn" class="area-btn px-3 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg flex items-center justify-center transition">
                                <i class="fas fa-hard-hat mr-2"></i> SSO
                            </button>
                            <button id="calidad-btn" class="area-btn px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg flex items-center justify-center transition">
                                <i class="fas fa-award mr-2"></i> Calidad
                            </button>
                        </div>
                        <input type="hidden" id="selected-area" value="">
                    </div>
                </div>
            </div>
            
            <!-- Camera Section -->
            <div class="bg-slate-800 rounded-xl p-6 shadow-xl fade-in">
                <h2 class="text-xl font-semibold mb-4 flex items-center">
                    <i class="fas fa-camera text-blue-400 mr-2"></i>
                    Cámara
                </h2>
                
                <div class="relative">
                    <!-- Camera Preview -->
                    <div id="camera-container" class="relative rounded-lg overflow-hidden bg-slate-900">
                        <video id="preview" autoplay muted class="w-full h-auto"></video>
                        <canvas id="canvas" class="hidden"></canvas>
                        
                        <!-- Watermark Overlay -->
                        <div id="watermark-overlay" class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/70 to-transparent">
                            <div id="watermark-text" class="text-white text-sm watermark">
                                <div class="font-bold text-lg">Q72 Ampliación Ruta S-839</div>
                                <div id="watermark-date" class="mt-1"></div>
                                <div id="watermark-coords" class="mt-1"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Capture Button -->
                    <div class="flex justify-center mt-4">
                        <button id="capture-btn" class="w-16 h-16 rounded-full bg-blue-600 hover:bg-blue-700 text-white flex items-center justify-center shadow-lg transition transform hover:scale-105">
                            <i class="fas fa-camera text-2xl"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Photo Gallery -->
                <div id="photo-gallery" class="mt-6 grid grid-cols-3 gap-2 hidden">
                    <h3 class="col-span-3 text-lg font-medium mb-2">Fotos tomadas:</h3>
                    <!-- Photos will be added here dynamically -->
                </div>
            </div>
            
            <!-- Map Section -->
            <div class="bg-slate-800 rounded-xl p-6 shadow-xl fade-in">
                <h2 class="text-xl font-semibold mb-4 flex items-center">
                    <i class="fas fa-map-marked-alt text-blue-400 mr-2"></i>
                    Ubicación
                </h2>
                
                <div id="map"></div>
                
                <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="bg-slate-700/50 p-3 rounded-lg">
                        <div class="text-sm text-slate-400">Coordenadas UTM</div>
                        <div id="utm-coords" class="font-mono text-blue-400">Esperando GPS...</div>
                    </div>
                    
                    <div class="bg-slate-700/50 p-3 rounded-lg">
                        <div class="text-sm text-slate-400">Huso</div>
                        <div id="utm-zone" class="font-mono text-blue-400">18S (WGS84)</div>
                    </div>
                </div>
            </div>
            
            <!-- Export Section -->
            <div class="bg-slate-800 rounded-xl p-6 shadow-xl fade-in">
                <h2 class="text-xl font-semibold mb-4 flex items-center">
                    <i class="fas fa-file-export text-blue-400 mr-2"></i>
                    Exportar
                </h2>
                
                <div class="flex flex-wrap gap-3">
                    <button id="export-kml" class="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg font-medium transition flex items-center disabled:opacity-50" disabled>
                        <i class="fas fa-map-marked-alt mr-2"></i> Exportar KML
                    </button>
                    
                    <button id="export-zip" class="px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg font-medium transition flex items-center disabled:opacity-50" disabled>
                        <i class="fas fa-file-archive mr-2"></i> Exportar ZIP
                    </button>
                    
                    <button id="clear-all" class="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white rounded-lg font-medium transition flex items-center">
                        <i class="fas fa-trash-alt mr-2"></i> Limpiar todo
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Photo Modal -->
    <div id="photo-modal" class="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 hidden">
        <div class="bg-slate-800 rounded-xl p-4 w-full max-w-2xl mx-4 shadow-2xl fade-in">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold">Vista previa de foto</h3>
                <button id="close-photo-modal" class="text-slate-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1">
                    <img id="modal-photo" src="" alt="Foto" class="w-full h-auto rounded-lg">
                </div>
                
                <div class="flex-1 bg-slate-700/50 p-4 rounded-lg">
                    <h4 class="font-medium mb-2">Metadatos:</h4>
                    <div id="photo-metadata" class="space-y-2 text-sm">
                        <!-- Metadata will be added here -->
                    </div>
                    
                    <button id="delete-photo" class="mt-4 px-3 py-1 bg-rose-600 hover:bg-rose-700 text-white rounded-lg text-sm font-medium transition">
                        <i class="fas fa-trash-alt mr-1"></i> Eliminar foto
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Leaflet JS -->
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <!-- JSZip -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <!-- FileSaver -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Variables
            let photos = [];
            let currentStream = null;
            let currentPosition = null;
            let map = null;
            let marker = null;
            let watchId = null;
            let selectedArea = '';
            
            // DOM Elements
            const preview = document.getElementById('preview');
            const canvas = document.getElementById('canvas');
            const captureBtn = document.getElementById('capture-btn');
            const photoGallery = document.getElementById('photo-gallery');
            const operatorNameInput = document.getElementById('operator-name');
            const selectedAreaInput = document.getElementById('selected-area');
            const watermarkCoords = document.getElementById('watermark-coords');
            const watermarkDate = document.getElementById('watermark-date');
            const gpsStatus = document.getElementById('gps-status');
            const utmCoords = document.getElementById('utm-coords');
            const utmZone = document.getElementById('utm-zone');
            const exportKmlBtn = document.getElementById('export-kml');
            const exportZipBtn = document.getElementById('export-zip');
            const clearAllBtn = document.getElementById('clear-all');
            const photoModal = document.getElementById('photo-modal');
            const modalPhoto = document.getElementById('modal-photo');
            const photoMetadata = document.getElementById('photo-metadata');
            const closePhotoModal = document.getElementById('close-photo-modal');
            const deletePhotoBtn = document.getElementById('delete-photo');
            const ambienteBtn = document.getElementById('ambiente-btn');
            const ssoBtn = document.getElementById('sso-btn');
            const calidadBtn = document.getElementById('calidad-btn');
            
            // Constants for UTM Zone 18S (South)
            const UTM_ZONE = 18;
            const UTM_ZONE_LETTER = 'S';
            const FALSE_EASTING = 500000;
            const FALSE_NORTHING = 10000000; // For southern hemisphere
            const SCALE_FACTOR = 0.9996;
            const EQUATORIAL_RADIUS = 6378137.0; // WGS84 equatorial radius in meters
            const FLATTENING = 1 / 298.257223563; // WGS84 flattening
            
            // Initialize components
            initMap();
            initCamera();
            startGPS();
            setupAreaButtons();
            updateWatermark();
            
            // Event Listeners
            operatorNameInput.addEventListener('input', updateWatermark);
            captureBtn.addEventListener('click', capturePhoto);
            exportKmlBtn.addEventListener('click', exportKML);
            exportZipBtn.addEventListener('click', exportZIP);
            clearAllBtn.addEventListener('click', clearAll);
            closePhotoModal.addEventListener('click', () => photoModal.classList.add('hidden'));
            
            // Functions
            function setupAreaButtons() {
                ambienteBtn.addEventListener('click', () => {
                    selectedArea = 'Medio Ambiente';
                    selectedAreaInput.value = selectedArea;
                    resetAreaButtons();
                    ambienteBtn.classList.add('ring-2', 'ring-offset-2', 'ring-emerald-400');
                });
                
                ssoBtn.addEventListener('click', () => {
                    selectedArea = 'SSO';
                    selectedAreaInput.value = selectedArea;
                    resetAreaButtons();
                    ssoBtn.classList.add('ring-2', 'ring-offset-2', 'ring-amber-400');
                });
                
                calidadBtn.addEventListener('click', () => {
                    selectedArea = 'Calidad';
                    selectedAreaInput.value = selectedArea;
                    resetAreaButtons();
                    calidadBtn.classList.add('ring-2', 'ring-offset-2', 'ring-blue-400');
                });
            }
            
            function resetAreaButtons() {
                ambienteBtn.classList.remove('ring-2', 'ring-offset-2', 'ring-emerald-400');
                ssoBtn.classList.remove('ring-2', 'ring-offset-2', 'ring-amber-400');
                calidadBtn.classList.remove('ring-2', 'ring-offset-2', 'ring-blue-400');
            }
            
            function initCamera() {
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    alert("La API de cámara no está disponible en este navegador");
                    return;
                }
                
                navigator.mediaDevices.getUserMedia({ 
                    video: { 
                        width: { ideal: 1280 },
                        height: { ideal: 720 },
                        facingMode: 'environment' 
                    } 
                })
                .then(stream => {
                    currentStream = stream;
                    preview.srcObject = stream;
                    
                    // Set canvas size to match video
                    preview.addEventListener('loadedmetadata', () => {
                        canvas.width = preview.videoWidth;
                        canvas.height = preview.videoHeight;
                    });
                    
                    return new Promise((resolve) => {
                        preview.onplaying = resolve;
                    });
                })
                .then(() => {
                    console.log("Cámara inicializada correctamente");
                })
                .catch(err => {
                    console.error("Error al acceder a la cámara:", err);
                    alert("No se pudo acceder a la cámara. Asegúrate de dar los permisos necesarios.");
                });
            }
            
            function initMap() {
                try {
                    map = L.map('map').setView([-34.6037, -58.3816], 13); // Default to Buenos Aires
                    
                    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                        maxZoom: 19
                    }).addTo(map);
                    
                    marker = L.marker([0, 0], {
                        icon: L.divIcon({
                            className: 'custom-marker',
                            html: '<i class="fas fa-map-marker-alt text-3xl text-blue-500"></i>',
                            iconSize: [30, 30],
                            iconAnchor: [15, 30]
                        }),
                        draggable: false
                    }).addTo(map);
                    
                    console.log("Mapa inicializado correctamente");
                } catch (error) {
                    console.error("Error al inicializar el mapa:", error);
                    alert("Error al cargar el mapa. Intenta recargar la página.");
                }
            }
            
            function startGPS() {
                if (!navigator.geolocation) {
                    alert("Geolocalización no soportada por tu navegador");
                    return;
                }
                
                gpsStatus.querySelector('div').classList.remove('bg-rose-500');
                gpsStatus.querySelector('div').classList.add('bg-amber-500');
                gpsStatus.querySelector('span').textContent = 'GPS: Conectando...';
                
                // First try to get current position quickly
                navigator.geolocation.getCurrentPosition(
                    position => {
                        handlePositionSuccess(position);
                    },
                    error => {
                        console.warn("Error inicial de GPS (getCurrentPosition):", error);
                        // Fall back to watchPosition if getCurrentPosition fails
                        startWatchingGPS();
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 5000,
                        maximumAge: 0
                    }
                );
            }
            
            function startWatchingGPS() {
                watchId = navigator.geolocation.watchPosition(
                    handlePositionSuccess,
                    handlePositionError,
                    {
                        enableHighAccuracy: true,
                        maximumAge: 30000,
                        timeout: 27000
                    }
                );
            }
            
            function handlePositionSuccess(position) {
                currentPosition = position;
                updatePositionInfo(position);
                updateWatermark();
                
                gpsStatus.querySelector('div').classList.remove('bg-amber-500', 'bg-rose-500');
                gpsStatus.querySelector('div').classList.add('bg-emerald-500');
                gpsStatus.querySelector('span').textContent = 'GPS: Conectado';
                
                console.log("Posición GPS obtenida:", position);
            }
            
            function handlePositionError(error) {
                console.error("Error de GPS:", error);
                gpsStatus.querySelector('div').classList.remove('bg-amber-500', 'bg-emerald-500');
                gpsStatus.querySelector('div').classList.add('bg-rose-500');
                
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        gpsStatus.querySelector('span').textContent = 'GPS: Permiso denegado';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        gpsStatus.querySelector('span').textContent = 'GPS: No disponible';
                        break;
                    case error.TIMEOUT:
                        gpsStatus.querySelector('span').textContent = 'GPS: Tiempo agotado';
                        break;
                    default:
                        gpsStatus.querySelector('span').textContent = 'GPS: Error desconocido';
                }
            }
            
            function updatePositionInfo(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                
                // Update map
                if (map) {
                    map.setView([lat, lng], 18);
                    marker.setLatLng([lat, lng]);
                }
                
                // Convert to UTM Zone 18S
                const utm = convertToUTMZone18S(lat, lng);
                
                // Update UTM display
                if (utmCoords) utmCoords.textContent = `Este: ${utm.easting.toFixed(2)}m, Norte: ${utm.northing.toFixed(2)}m`;
                if (utmZone) utmZone.textContent = `18S (WGS84)`;
                
                return utm;
            }
            
            function convertToUTMZone18S(lat, lng) {
                // This is a simplified UTM conversion for Zone 18S
                // Based on Karney's algorithm (simplified for demo purposes)
                
                // Check if longitude is within zone 18 (-78° to -72°)
                if (lng < -78 || lng >= -72) {
                    console.warn(`Longitud ${lng}° está fuera del huso 18 (-78° a -72°)`);
                }
                
                // Check if latitude is in southern hemisphere
                const isSouthernHemisphere = lat < 0;
                
                // Convert to radians
                const latRad = lat * Math.PI / 180;
                const lngRad = lng * Math.PI / 180;
                
                // Central meridian for zone 18 (-75°)
                const lng0Rad = (-75) * Math.PI / 180;
                
                // Calculate delta longitude
                const deltaLng = lngRad - lng0Rad;
                
                // WGS84 parameters
                const a = EQUATORIAL_RADIUS;
                const f = FLATTENING;
                const k0 = SCALE_FACTOR;
                
                // Intermediate calculations
                const e = Math.sqrt(f * (2 - f));
                const n = f / (2 - f);
                const A = a / (1 + n) * (1 + n*n/4 + n*n*n*n/64);
                
                const t = Math.sinh(Math.atanh(Math.sin(latRad)) - (2 * Math.sqrt(n)) / (1 + n) * Math.atanh((2 * Math.sqrt(n)) / (1 + n) * Math.sin(latRad)));
                const xiPrim = Math.atan(t / Math.cos(deltaLng));
                const etaPrim = Math.atanh(Math.sin(deltaLng) / Math.sqrt(1 + t * t));
                
                // Calculate easting and northing
                const easting = FALSE_EASTING + k0 * A * etaPrim * (1 + 
                    (etaPrim*etaPrim)/6 * (1 - t*t + (etaPrim*etaPrim)/20 * (5 - 18*t*t + t*t*t*t + 14*etaPrim*etaPrim - 58*t*t*etaPrim*etaPrim)));
                
                let northing = k0 * A * xiPrim * (1 + 
                    (etaPrim*etaPrim)/2 * (1 + (etaPrim*etaPrim)/12 * (5 - t*t + 9*etaPrim*etaPrim + 4*etaPrim*etaPrim*etaPrim*etaPrim)));
                
                // Adjust northing for southern hemisphere
                if (isSouthernHemisphere) {
                    northing += FALSE_NORTHING;
                }
                
                return {
                    easting: easting,
                    northing: northing,
                    zone: UTM_ZONE,
                    zoneLetter: UTM_ZONE_LETTER
                };
            }
            
            function updateWatermark() {
                const now = new Date();
                watermarkDate.textContent = now.toLocaleString();
                
                if (currentPosition) {
                    const utm = updatePositionInfo(currentPosition);
                    watermarkCoords.textContent = `UTM ${utm.zone}${utm.zoneLetter} (WGS84): E ${utm.easting.toFixed(2)}m, N ${utm.northing.toFixed(2)}m`;
                } else {
                    watermarkCoords.textContent = "Coordenadas no disponibles";
                }
            }
            
            function capturePhoto() {
                if (!currentStream) {
                    alert("La cámara no está lista. Intenta recargar la página.");
                    return;
                }
                
                if (!currentPosition) {
                    alert("Esperando conexión GPS... Por favor espera.");
                    return;
                }
                
                if (!selectedArea) {
                    alert("Por favor selecciona un área antes de tomar la foto");
                    return;
                }
                
                // Get canvas context
                const context = canvas.getContext('2d');
                
                // Draw current frame to canvas
                context.drawImage(preview, 0, 0, canvas.width, canvas.height);
                
                // Add watermark text directly to canvas
                context.font = '16px Arial';
                context.fillStyle = 'white';
                context.textAlign = 'left';
                context.textBaseline = 'bottom';
                
                const name = operatorNameInput.value || "Operador no especificado";
                
                const utm = updatePositionInfo(currentPosition);
                const now = new Date();
                
                // Draw watermark text with shadow effect
                context.shadowColor = 'black';
                context.shadowBlur = 5;
                
                // Título fijo
                context.font = 'bold 20px Arial';
                context.fillText('Q72 Ampliación Ruta S-839', 20, canvas.height - 60);
                
                // Fecha y hora
                context.font = '16px Arial';
                context.fillText(now.toLocaleString(), 20, canvas.height - 40);
                
                // Coordenadas UTM
                context.fillText(`UTM ${utm.zone}${utm.zoneLetter} (WGS84): E ${utm.easting.toFixed(2)}m, N ${utm.northing.toFixed(2)}m`, 20, canvas.height - 20);
                
                context.shadowBlur = 0;
                
                // Create photo object with metadata
                const photo = {
                    id: Date.now(),
                    dataUrl: canvas.toDataURL('image/jpeg', 0.9),
                    timestamp: now.toISOString(),
                    operator: name,
                    area: selectedArea,
                    coordinates: {
                        lat: currentPosition.coords.latitude,
                        lng: currentPosition.coords.longitude,
                        utm: utm
                    }
                };
                
                photos.push(photo);
                savePhotos();
                renderPhotoGallery();
                updateExportButtons();
                
                // Show success animation
                captureBtn.innerHTML = '<i class="fas fa-check"></i>';
                captureBtn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
                captureBtn.classList.add('bg-emerald-600', 'hover:bg-emerald-700');
                
                setTimeout(() => {
                    captureBtn.innerHTML = '<i class="fas fa-camera"></i>';
                    captureBtn.classList.remove('bg-emerald-600', 'hover:bg-emerald-700');
                    captureBtn.classList.add('bg-blue-600', 'hover:bg-blue-700');
                }, 1000);
            }
            
            function renderPhotoGallery() {
                if (photos.length === 0) {
                    photoGallery.classList.add('hidden');
                    return;
                }
                
                photoGallery.classList.remove('hidden');
                photoGallery.innerHTML = '<h3 class="col-span-3 text-lg font-medium mb-2">Fotos tomadas:</h3>';
                
                photos.forEach((photo, index) => {
                    const photoElement = document.createElement('div');
                    photoElement.className = 'relative group cursor-pointer';
                    photoElement.innerHTML = `
                        <img src="${photo.dataUrl}" alt="Foto ${index + 1}" class="w-full h-24 object-cover rounded-lg">
                        <div class="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition">
                            <span class="text-white text-sm">${index + 1}</span>
                        </div>
                    `;
                    
                    photoElement.addEventListener('click', () => showPhotoModal(photo));
                    photoGallery.appendChild(photoElement);
                });
            }
            
            function showPhotoModal(photo) {
                modalPhoto.src = photo.dataUrl;
                
                // Format metadata
                const date = new Date(photo.timestamp);
                photoMetadata.innerHTML = `
                    <div><strong>Operador:</strong> ${photo.operator}</div>
                    <div><strong>Área:</strong> ${photo.area}</div>
                    <div><strong>Fecha:</strong> ${date.toLocaleString()}</div>
                    <div><strong>Coordenadas:</strong></div>
                    <div class="pl-4">Lat: ${photo.coordinates.lat.toFixed(6)}</div>
                    <div class="pl-4">Lng: ${photo.coordinates.lng.toFixed(6)}</div>
                    <div class="pl-4">UTM ${photo.coordinates.utm.zone}${photo.coordinates.utm.zoneLetter}: E ${photo.coordinates.utm.easting.toFixed(2)}m, N ${photo.coordinates.utm.northing.toFixed(2)}m</div>
                `;
                
                // Set up delete button
                deletePhotoBtn.onclick = () => {
                    photos = photos.filter(p => p.id !== photo.id);
                    savePhotos();
                    renderPhotoGallery();
                    updateExportButtons();
                    photoModal.classList.add('hidden');
                };
                
                photoModal.classList.remove('hidden');
            }
            
            function exportKML() {
                if (photos.length === 0) return;
                
                // Group photos by area
                const photosByArea = {};
                photos.forEach(photo => {
                    if (!photosByArea[photo.area]) {
                        photosByArea[photo.area] = [];
                    }
                    photosByArea[photo.area].push(photo);
                });
                
                // Create a ZIP file with one KML per area
                const zip = new JSZip();
                
                for (const area in photosByArea) {
                    // Create KML content for this area
                    let kml = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
    <Document>
        <name>Fotos ${area}</name>
        <description>Fotos tomadas para el área de ${area}</description>`;
                    
                    photosByArea[area].forEach(photo => {
                        // Convert image to base64 without data URL prefix
                        const base64Image = photo.dataUrl.split(',')[1];
                        
                        kml += `
        <Placemark>
            <name>Foto ${new Date(photo.timestamp).toLocaleString()}</name>
            <description>
                <![CDATA[
                <h3>Foto georreferenciada</h3>
                <p><strong>Operador:</strong> ${photo.operator}</p>
                <p><strong>Área:</strong> ${photo.area}</p>
                <p><strong>Fecha:</strong> ${new Date(photo.timestamp).toLocaleString()}</p>
                <p><strong>Coordenadas UTM:</strong> ${photo.coordinates.utm.zone}${photo.coordinates.utm.zoneLetter} E ${photo.coordinates.utm.easting.toFixed(2)}m, N ${photo.coordinates.utm.northing.toFixed(2)}m</p>
                <img src="data:image/jpeg;base64,${base64Image}" width="400" />
                ]]>
            </description>
            <Point>
                <coordinates>${photo.coordinates.lng},${photo.coordinates.lat},0</coordinates>
            </Point>
        </Placemark>`;
                    });
                    
                    kml += `
    </Document>
</kml>`;
                    
                    // Add to ZIP
                    const filename = `fotos_${area.replace(/\s+/g, '_').toLowerCase()}.kml`;
                    zip.file(filename, kml);
                }
                
                // Generate ZIP and download
                zip.generateAsync({ type: "blob" }).then(content => {
                    saveAs(content, "fotos_georreferenciadas_por_area.zip");
                });
            }
            
            function exportZIP() {
                if (photos.length === 0) return;
                
                const zip = new JSZip();
                const imgFolder = zip.folder("fotos");
                const kmlFolder = zip.folder("kml");
                
                // Group photos by area
                const photosByArea = {};
                photos.forEach(photo => {
                    if (!photosByArea[photo.area]) {
                        photosByArea[photo.area] = [];
                    }
                    photosByArea[photo.area].push(photo);
                });
                
                // Add photos and create KML for each area
                for (const area in photosByArea) {
                    const areaImgFolder = imgFolder.folder(area);
                    let photoIndex = 1;
                    
                    // Create KML content for this area
                    let kml = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
    <Document>
        <name>Fotos ${area}</name>
        <description>Fotos tomadas para el área de ${area}</description>`;
                    
                    photosByArea[area].forEach(photo => {
                        // Extract base64 data
                        const base64Data = photo.dataUrl.split(',')[1];
                        areaImgFolder.file(`foto_${photoIndex}.jpg`, base64Data, { base64: true });
                        
                        kml += `
        <Placemark>
            <name>Foto ${new Date(photo.timestamp).toLocaleString()}</name>
            <description>
                <![CDATA[
                <h3>Foto georreferenciada</h3>
                <p><strong>Operador:</strong> ${photo.operator}</p>
                <p><strong>Área:</strong> ${photo.area}</p>
                <p><strong>Fecha:</strong> ${new Date(photo.timestamp).toLocaleString()}</p>
                <p><strong>Coordenadas UTM:</strong> ${photo.coordinates.utm.zone}${photo.coordinates.utm.zoneLetter} E ${photo.coordinates.utm.easting.toFixed(2)}m, N ${photo.coordinates.utm.northing.toFixed(2)}m</p>
                <img src="../fotos/${area}/foto_${photoIndex}.jpg" width="400" />
                ]]>
            </description>
            <Point>
                <coordinates>${photo.coordinates.lng},${photo.coordinates.lat},0</coordinates>
            </Point>
        </Placemark>`;
                        
                        photoIndex++;
                    });
                    
                    kml += `
    </Document>
</kml>`;
                    
                    // Add KML for this area
                    const filename = `fotos_${area.replace(/\s+/g, '_').toLowerCase()}.kml`;
                    kmlFolder.file(filename, kml);
                }
                
                // Generate ZIP and download
                zip.generateAsync({ type: "blob" }).then(content => {
                    saveAs(content, "fotos_georreferenciadas_completas.zip");
                });
            }
            
            function clearAll() {
                if (confirm("¿Estás seguro de que deseas eliminar todas las fotos?")) {
                    photos = [];
                    savePhotos();
                    renderPhotoGallery();
                    updateExportButtons();
                }
            }
            
            function savePhotos() {
                localStorage.setItem('geoPhotos', JSON.stringify(photos));
            }
            
            function loadPhotos() {
                const savedPhotos = localStorage.getItem('geoPhotos');
                if (savedPhotos) {
                    photos = JSON.parse(savedPhotos);
                    renderPhotoGallery();
                    updateExportButtons();
                }
            }
            
            function updateExportButtons() {
                exportKmlBtn.disabled = photos.length === 0;
                exportZipBtn.disabled = photos.length === 0;
            }
            
            // Initialize from storage
            loadPhotos();
            
            // Update watermark periodically
            setInterval(updateWatermark, 1000);
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=ignaciomdr/geocam2" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>