-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1857 lines (1746 loc) · 80.2 KB
/
Copy pathindex.html
File metadata and controls
1857 lines (1746 loc) · 80.2 KB
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bengaluru Wards Comparison Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
html, body {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
overflow: hidden;
}
#map-container {
display: grid;
width: 100vw;
height: calc(100vh - 70px);
min-height: 0;
overflow: hidden;
grid-gap: 2px;
background: #111;
/* Default: 2 maps side by side */
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr;
}
.map-section {
min-width: 0;
min-height: 0;
position: relative;
border: 1px solid #111;
border-radius: 0;
margin: 0;
display: flex;
flex-direction: column;
background: #f8f8f8;
overflow: hidden;
width: 100%;
height: 100%;
box-sizing: border-box;
}
.map {
flex: 1 1 auto;
min-height: 0;
min-width: 0;
border-radius: 0;
overflow: hidden;
}
.split-btn {
background: #1976d2;
color: #fff;
border: none;
border-radius: 4px;
padding: 4px 10px;
cursor: pointer;
font-size: 0.95em;
}
/* Comparison Panel Styles */
#comparison-panel {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.32);
z-index: 2000;
display: none;
align-items: center;
justify-content: center;
}
#comparison-panel.active {
display: flex;
}
#comparison-panel-content {
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 24px rgba(0,0,0,0.18);
padding: 0;
min-width: 800px;
max-width: 95vw;
max-height: 90vh;
overflow: hidden;
position: relative;
display: flex;
flex-direction: row;
}
#comparison-left-panel {
flex: 0 0 350px;
width: 350px;
padding: 32px 24px 24px 28px;
overflow-y: auto;
border-right: 1px solid #e0e0e0;
}
#comparison-right-panel {
flex: 0 0 1200px;
width: 1200px;
display: flex;
flex-direction: column;
background: #f9f9f9;
}
#comparison-map-legend {
position: absolute;
bottom: 10px;
right: 10px;
background: rgba(255,255,255,0.95);
padding: 8px 12px;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
font-size: 0.85em;
z-index: 1000;
}
#comparison-panel h3 {
margin: 0 0 16px 0;
color: #ff9800;
font-size: 1.2em;
}
.comparison-result {
margin: 12px 0;
padding: 10px;
background: #f5f5f5;
border-radius: 4px;
border-left: 4px solid #2196F3;
}
.comparison-result.exact-match {
border-left-color: #4CAF50;
}
.comparison-result.partial-match {
border-left-color: #FF9800;
// Direct mapping for feature overlays
window.comparisonFeatureOverlayMap = [];
overlappingFeatures.forEach((item, idx) => {
.comparison-result.no-match {
border-left-color: #F44336;
}
@media (max-width: 900px) {
#map-container {
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr 1fr 1fr;
height: calc(100vh - 70px);
}
.map-section {
min-width: 0;
min-height: 0;
}
}
</style>
</head>
<body>
<div style="display: flex; align-items: center; justify-content: center; margin-top: 16px; margin-bottom: 8px; gap: 12px; width: 100%; max-width: 1200px; margin-left: auto; margin-right: auto;">
<div id="svg-patterns" style="display:none"></div>
<h2 style="margin: 0 12px 0 0; flex-shrink: 0;">GBA Area Compare</h2>
<div id="search-bar-container" style="margin-left: auto; position: relative; min-width: 260px; max-width: 420px; width: 100%; display: flex; align-items: center; gap: 6px;">
<input id="location-search" type="text" placeholder="Search ward, village, or settlement..." style="flex:1; padding: 7px 10px; font-size: 1em; border: 1.5px solid #bbb; border-radius: 4px; outline: none;" autocomplete="off">
<div id="autocomplete-list" style="position: absolute; left: 0; top: 100%; z-index: 1000; background: #fff; border: 1px solid #ccc; border-radius: 0 0 4px 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); width: 100%; display: none;"></div>
</div>
<div id="toggle-btn-group" style="display: flex; margin-left: 16px; background: #e3eaf3; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.04);">
<button id="btn-1x2" class="toggle-btn toggle-btn-active" title="1x2 Grid" style="border: none; background: none; padding: 0 14px; height: 36px; display: flex; align-items: center; gap: 6px; font-size: 1em; color: #1976d2; background: #fff; border-right: 1.5px solid #c7d0e0; cursor: pointer; transition: background 0.15s, color 0.15s; outline: none;">
<svg width="28" height="20" viewBox="0 0 28 20"><rect x="2" y="2" width="10" height="16" rx="2" fill="#f8f8f8" stroke="#1976d2" stroke-width="2"/><rect x="16" y="2" width="10" height="16" rx="2" fill="#f8f8f8" stroke="#1976d2" stroke-width="2"/></svg>
</button>
<button id="btn-2x2" class="toggle-btn" title="2x2 Grid" style="border: none; background: none; padding: 0 14px; height: 36px; display: flex; align-items: center; gap: 6px; font-size: 1em; color: #222; background: transparent; cursor: pointer; transition: background 0.15s, color 0.15s; outline: none;">
<svg width="28" height="20" viewBox="0 0 28 20"><rect x="2" y="2" width="10" height="7" rx="2" fill="#f8f8f8" stroke="#1976d2" stroke-width="2"/><rect x="16" y="2" width="10" height="7" rx="2" fill="#f8f8f8" stroke="#1976d2" stroke-width="2"/><rect x="2" y="11" width="10" height="7" rx="2" fill="#f8f8f8" stroke="#1976d2" stroke-width="2"/><rect x="16" y="11" width="10" height="7" rx="2" fill="#f8f8f8" stroke="#1976d2" stroke-width="2"/></svg>
</button>
</div>
<button id="compare-polygons-btn" class="split-btn" style="margin-left: auto; font-weight: 600; background: #ff9800; color: #fff;">🔍 Area Compare</button>
</div>
<div id="map-container"></div>
<!-- Comparison Panel -->
<div id="comparison-panel">
<div id="comparison-panel-content">
<button id="close-comparison-panel" style="position:absolute; top:10px; right:14px; background:none; border:none; font-size:1.5em; color:#888; cursor:pointer; z-index:10;">×</button>
<!-- Left Panel: Controls and Results -->
<div id="comparison-left-panel">
<h3 style="margin:0 0 20px 0; color:#ff9800; font-size:1.2em;">🔍 Area Compare</h3>
<div id="comparison-content">
<div style="margin-bottom:16px;">
<label style="font-weight:600; display:block; margin-bottom:6px;">Base Layer</label>
<select id="comparison-base-layer" style="width:100%; padding:8px; font-size:1em; border:1px solid #ccc; border-radius:4px;">
<option value="" disabled selected>Select layer...</option>
</select>
</div>
<div style="margin-bottom:16px;">
<label style="font-weight:600; display:block; margin-bottom:6px;">Select Feature</label>
<input id="comparison-search" type="text" placeholder="Search feature..." style="width:100%; padding:8px; font-size:1em; border:1px solid #ccc; border-radius:4px;" autocomplete="off">
<div id="comparison-autocomplete" style="position:relative;"></div>
</div>
<div style="margin-bottom:16px;">
<label style="font-weight:600; display:block; margin-bottom:6px;">Compare Layer</label>
<select id="comparison-compare-layer" style="width:100%; padding:8px; font-size:1em; border:1px solid #ccc; border-radius:4px;">
<option value="" disabled selected>Select layer to compare...</option>
</select>
</div>
<div style="display:flex; gap:10px; margin-bottom:16px;">
<button id="run-comparison-btn" style="flex:1; padding:10px; background:#1976d2; color:#fff; border:none; border-radius:4px; font-size:1.05em; font-weight:600; cursor:pointer;">Compare</button>
<button id="reset-comparison-btn" style="flex:1; padding:10px; background:#bbb; color:#222; border:none; border-radius:4px; font-size:1.05em; font-weight:600; cursor:pointer;">Reset</button>
</div>
<div id="comparison-results" style="margin-top:16px;"></div>
</div>
</div>
<!-- Right Panel: Map Viewport -->
<div id="comparison-right-panel">
<div id="comparison-map-container" style="width:100%; height:100%; display:none; position:relative;">
<div id="comparison-map" style="width:100%; height:100%;"></div>
</div>
</div>
</div>
</div>
<!-- SVG Patterns for hatching -->
<svg width="0" height="0" style="position:absolute;">
<defs>
<pattern id="diagonalHatch" patternUnits="userSpaceOnUse" width="8" height="8">
<path d="M-1,1 l2,-2 M0,8 l8,-8 M7,9 l2,-2" style="stroke:#F44336; stroke-width:1" />
</pattern>
<pattern id="blueHatch" patternUnits="userSpaceOnUse" width="8" height="8">
<path d="M-1,1 l2,-2 M0,8 l8,-8 M7,9 l2,-2" style="stroke:#2196F3; stroke-width:1" />
</pattern>
<pattern id="greenHatch" patternUnits="userSpaceOnUse" width="8" height="8">
<path d="M-1,1 l2,-2 M0,8 l8,-8 M7,9 l2,-2" style="stroke:#4CAF50; stroke-width:1" />
</pattern>
</defs>
</svg>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://jieter.github.io/Leaflet.Sync/L.Map.Sync.js"></script>
<script src="https://unpkg.com/@turf/turf@6/turf.min.js"></script>
<script>
// ============================================================================
// CONFIGURATION
// ============================================================================
const LAYER_OPTIONS = [
{ label: 'New GBA Wards', url: 'geojson/gba_wards.geojson', color: 'green', searchField: 'ward_name' },
{ label: 'BBMP Wards', url: 'geojson/bbmp_wards.geojson', color: 'blue', searchField: 'Ward Name (en)' },
{ label: 'GBA Final Wards', url: 'geojson/GBA_Final_Wards_369.geojson', color: 'teal', searchField: 'ward_name' },
{ label: 'Villages', url: 'geojson/villages.geojson', color: 'orange', searchField: 'Village Name' },
{ label: 'Settlements', url: 'geojson/bbmp_settlements.geojson', color: 'purple', searchField: 'KGISVill_2' },
{ label: 'GBA Zones', url: 'geojson/zones.geojson', color: 'red', searchField: null }
];
const SEARCHABLE_LAYERS = LAYER_OPTIONS.filter(l => l.searchField);
// Color palette for overlapping features (global for comparison logic)
const featureColors = [
'#2196F3', // Blue
'#9C27B0', // Purple
'#E91E63', // Pink
'#00BCD4', // Cyan
'#FF5722', // Deep Orange
'#009688', // Teal
'#FFC107', // Amber
'#795548', // Brown
'#607D8B', // Blue Grey
'#3F51B5' // Indigo
];
const initialCenter = [12.9716, 77.5946];
const initialZoom = 11;
const maxSections = 4;
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
// Get filtered popup properties based on layer type
function getPopupProps(label, props) {
switch (label) {
case 'GBA Final Wards':
case 'New GBA Wards':
return `<b>Corporation</b>: ${props.Corporation || ''}<br><b>Ward Name</b>: ${props.ward_name || ''}`;
case 'BBMP Wards':
return `<b>Ward Name (en)</b>: ${props['Ward Name (en)'] || ''}`;
case 'Villages':
return `<b>fid</b>: ${props.fid || ''}<br><b>Village Name</b>: ${props['Village Name'] || ''}`;
case 'Settlements':
return `<b>KGISVillageID</b>: ${props.KGISVillageID || ''}<br><b>Category</b>: ${props.Category || ''}<br><b>Kharab</b>: ${props.Kharab || ''}<br><b>Surveynumber_Old</b>: ${props.Surveynumber_Old || ''}<br><b>KGISVill_2</b>: ${props.KGISVill_2 || ''}`;
case 'GBA Zones':
return `<b>Corporation/Zone</b>: ${props['Corporation/Zone'] || ''}`;
default:
return Object.entries(props).map(([k,v]) => `<b>${k}</b>: ${v}`).join('<br>');
}
}
// Create popup HTML with lat/lng copy button
function createPopupContent(layerLabel, layerColor, props, lat, lng) {
const propsHtml = getPopupProps(layerLabel, props);
const copyHtml = (lat && lng) ?
`<div style='margin-top:6px;font-size:0.97em;'>Lat: <b>${lat.toFixed ? lat.toFixed(6) : lat}</b><br>Lng: <b>${lng.toFixed ? lng.toFixed(6) : lng}</b><br><button id='copy-latlng-btn' style='margin-top:4px;padding:2px 10px;font-size:0.98em;cursor:pointer;'>Copy</button></div>`
: '';
return `<h4 style="margin:0 0 5px 0;font-size:14px;color:${layerColor}">${layerLabel}</h4>${propsHtml}${copyHtml}`;
}
// Attach copy button handler to popup
function attachCopyButtonHandler(lat, lng) {
setTimeout(() => {
const btn = document.getElementById('copy-latlng-btn');
if (btn && lat && lng) {
btn.onclick = function() {
navigator.clipboard.writeText(`${lat}, ${lng}`);
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy'; }, 1200);
};
}
}, 100);
}
// ============================================================================
// SEARCH & AUTOCOMPLETE
// ============================================================================
let searchIndex = [];
async function buildSearchIndex() {
searchIndex = [];
for (const layer of SEARCHABLE_LAYERS) {
try {
const resp = await fetch(layer.url);
if (!resp.ok) continue;
const data = await resp.json();
if (!data.features) continue;
for (const feat of data.features) {
const val = feat.properties[layer.searchField];
if (val && typeof val === 'string' && val.trim().length > 0) {
searchIndex.push({
label: val.trim(),
layerLabel: layer.label,
layerIdx: LAYER_OPTIONS.indexOf(layer),
feature: feat
});
}
}
} catch (e) { console.warn('Error loading for search index:', layer.label, e); }
}
// Sort alphabetically
searchIndex.sort((a, b) => a.label.localeCompare(b.label));
}
// --- Autocomplete UI logic ---
const searchInput = document.getElementById('location-search');
const autocompleteList = document.getElementById('autocomplete-list');
let currentFocus = -1;
function closeAutocomplete() {
autocompleteList.style.display = 'none';
autocompleteList.innerHTML = '';
currentFocus = -1;
}
function highlightFeatureOnMaps(selected) {
mapSections.forEach((ms) => {
// Map 0: multi-layer
if (ms.index === 0 && Array.isArray(ms.geoLayers) && ms.geoLayers.length > 0) {
if (ms.loadedLayers && ms.loadedLayers.includes(selected.layerIdx)) {
highlightFeatureInMultiLayers(ms, selected);
}
} else if (ms.index !== 0 && ms.geoLayer) {
// For other maps, check if the loadedLayer matches the selected layerIdx
if (typeof ms.loadedLayer === 'number' && ms.loadedLayer === selected.layerIdx) {
highlightFeatureInLayer(ms, selected);
}
}
});
}
function highlightFeatureInMultiLayers(ms, selected) {
// Find the geoLayer in ms.geoLayers that matches selected.layerIdx
const field = LAYER_OPTIONS[selected.layerIdx].searchField;
const selectedVal = (selected.feature.properties[field] || '').toString().trim().toLowerCase();
ms.geoLayers.forEach((geoLayer, i) => {
// Only check the correct layer
// We don't have a direct reference to which geoLayer is for which layerIdx, so check a feature property
let found = false;
geoLayer.eachLayer(layer => {
if (!layer.feature) return;
if (layer.feature.properties && selected.feature.properties) {
const layerVal = (layer.feature.properties[field] || '').toString().trim().toLowerCase();
if (field && layerVal === selectedVal) {
// Zoom to feature
if (!found) {
if (layer.getBounds) {
ms.map.fitBounds(layer.getBounds(), { maxZoom: 16 });
} else if (layer.getLatLng) {
ms.map.setView(layer.getLatLng(), 16);
}
found = true;
}
// Flash/highlight: set style, open popup
if (layer.setStyle) {
layer.setStyle({ color: '#ff6600', weight: 4, fillOpacity: 0.3 });
setTimeout(() => {
layer.setStyle({ color: LAYER_OPTIONS[selected.layerIdx].color, weight: 2, fillOpacity: 0.1 });
}, 1800);
}
if (layer.openPopup) {
layer.openPopup();
}
}
}
});
});
}
function highlightFeatureInLayer(ms, selected) {
if (!ms.geoLayer) return;
const field = LAYER_OPTIONS[selected.layerIdx].searchField;
const selectedVal = (selected.feature.properties[field] || '').toString().trim().toLowerCase();
ms.geoLayer.eachLayer(layer => {
if (!layer.feature) return;
if (layer.feature.properties && selected.feature.properties) {
const layerVal = (layer.feature.properties[field] || '').toString().trim().toLowerCase();
if (field && layerVal === selectedVal) {
// Zoom to feature
if (layer.getBounds) {
ms.map.fitBounds(layer.getBounds(), { maxZoom: 16 });
} else if (layer.getLatLng) {
ms.map.setView(layer.getLatLng(), 16);
}
// Flash/highlight: set style, open popup
if (layer.setStyle) {
layer.setStyle({ color: '#ff6600', weight: 4, fillOpacity: 0.3 });
setTimeout(() => {
layer.setStyle({ color: LAYER_OPTIONS[selected.layerIdx].color, weight: 2, fillOpacity: 0.1 });
}, 1800);
}
if (layer.openPopup) {
layer.openPopup();
}
}
}
});
}
async function showAutocomplete(val) {
closeAutocomplete();
if (!val || val.length < 2) return;
const matches = searchIndex.filter(item => item.label.toLowerCase().includes(val.toLowerCase()));
let results = [];
// Add geojson feature results
matches.slice(0, 10).forEach(item => {
results.push({
type: 'geojson',
label: item.label,
layerLabel: item.layerLabel,
item
});
});
// Lat/lng search: detect "lat, lng" pattern
const latlngRegex = /^\s*(-?\d{1,2}\.\d+)[,\s]+(-?\d{1,3}\.\d+)\s*$/;
const latlngMatch = val.match(latlngRegex);
if (latlngMatch) {
const lat = parseFloat(latlngMatch[1]);
const lng = parseFloat(latlngMatch[2]);
if (!isNaN(lat) && !isNaN(lng)) {
results.push({
type: 'latlng',
label: `Lat/Lng: ${lat}, ${lng}`,
lat, lng
});
}
}
// Base map search (Nominatim)
let nominatimResults = [];
try {
const resp = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(val)}&limit=5&addressdetails=1`);
if (resp.ok) {
const data = await resp.json();
if (Array.isArray(data)) {
nominatimResults = data.map(place => ({
type: 'nominatim',
label: place.display_name,
lat: parseFloat(place.lat),
lng: parseFloat(place.lon)
}));
}
}
} catch (e) { /* ignore errors */ }
nominatimResults.forEach(r => results.push(r));
if (results.length === 0) return;
autocompleteList.style.display = 'block';
autocompleteList.innerHTML = '';
results.forEach((result, idx) => {
const div = document.createElement('div');
div.style.padding = '7px 12px';
div.style.cursor = 'pointer';
div.style.borderBottom = '1px solid #eee';
if (result.type === 'geojson') {
div.innerHTML = `<span style="font-weight:600">${result.label}</span> <span style="color:#888;font-size:0.95em;">(Geo Layer: ${result.layerLabel})</span>`;
} else if (result.type === 'latlng') {
div.innerHTML = `<span style="font-weight:600">${result.label}</span> <span style="color:#1976d2;font-size:0.95em;">(Lat/Lng Search)</span>`;
} else if (result.type === 'nominatim') {
div.innerHTML = `<span style="font-weight:600">${result.label}</span> <span style="color:#43a047;font-size:0.95em;">(Base Map)</span>`;
}
div.onmousedown = (e) => {
e.preventDefault();
searchInput.value = result.label;
closeAutocomplete();
if (result.type === 'geojson') {
highlightFeatureOnMaps(result.item);
} else if (result.type === 'latlng' || result.type === 'nominatim') {
// Remove previous search markers if any
if (window._searchMarkers) {
window._searchMarkers.forEach(m => m.remove && m.remove());
}
window._searchMarkers = [];
// Zoom and add marker to all maps
mapSections.forEach(ms => {
ms.map.setView([result.lat, result.lng], 16);
const marker = L.marker([result.lat, result.lng], {
icon: L.icon({
iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
shadowSize: [41, 41]
})
}).addTo(ms.map);
window._searchMarkers.push(marker);
});
}
};
autocompleteList.appendChild(div);
});
}
searchInput.addEventListener('input', function(e) {
showAutocomplete(this.value);
});
searchInput.addEventListener('keydown', function(e) {
let items = autocompleteList.getElementsByTagName('div');
if (e.key === 'ArrowDown') {
currentFocus++;
if (currentFocus >= items.length) currentFocus = 0;
setActive(items);
} else if (e.key === 'ArrowUp') {
currentFocus--;
if (currentFocus < 0) currentFocus = items.length - 1;
setActive(items);
} else if (e.key === 'Enter') {
e.preventDefault();
if (currentFocus > -1 && items[currentFocus]) {
items[currentFocus].dispatchEvent(new MouseEvent('mousedown'));
}
}
});
function setActive(items) {
for (let i = 0; i < items.length; i++) {
items[i].style.background = '#fff';
}
if (currentFocus > -1 && items[currentFocus]) {
items[currentFocus].style.background = '#e3f0ff';
items[currentFocus].scrollIntoView({ block: 'nearest' });
}
}
document.addEventListener('click', function(e) {
if (e.target !== searchInput) closeAutocomplete();
});
// Call on page load
buildSearchIndex();
// ============================================================================
// MAP MANAGEMENT
// ============================================================================
let mapSections = [];
function createMapSection(idx) {
const section = document.createElement('div');
section.className = 'map-section';
section.id = `map-section-${idx}`;
// Map div
const mapDiv = document.createElement('div');
mapDiv.className = 'map';
mapDiv.id = `map${idx}`;
section.appendChild(mapDiv);
return section;
}
// Dynamically update grid layout based on actual DOM map-section count
function updateGridLayout() {
const container = document.getElementById('map-container');
// Use DOM children count so layout matches what's rendered
const count = container.querySelectorAll('.map-section').length;
// Reset defaults
container.style.gridGap = '2px';
container.style.background = '#f0f0f0';
if (count <= 1) {
// Single map: full width, single row
container.style.gridTemplateColumns = '1fr';
container.style.gridTemplateRows = '1fr';
} else if (count === 2) {
// Two maps: side-by-side
container.style.gridTemplateColumns = '1fr 1fr';
container.style.gridTemplateRows = '1fr';
} else if (count === 3) {
// Three maps: two on top, one below
container.style.gridTemplateColumns = '1fr 1fr';
container.style.gridTemplateRows = '1fr 1fr';
} else if (count >= 4) {
// Four maps: 2x2
container.style.gridTemplateColumns = '1fr 1fr';
container.style.gridTemplateRows = '1fr 1fr';
}
// Force maps to resize shortly after layout change
setTimeout(() => {
mapSections.forEach(ms => { try { ms.map.invalidateSize(); } catch(e){} });
}, 120);
}
function addMapSection() {
if (mapSections.length >= maxSections) return;
const idx = mapSections.length;
const section = createMapSection(idx);
document.getElementById('map-container').appendChild(section);
// Create Leaflet map
const map = L.map(`map${idx}`, {
center: initialCenter,
zoom: initialZoom,
zoomControl: idx === 0, // Only first map has zoom control
scrollWheelZoom: true
});
// OSM base
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 19,
opacity: 0.85
}).addTo(map);
// --- Multi-layer logic for map 0 ---
// Add click handler to show lat/lng popup with copy button
map.on('click', function(e) {
// Only show if not clicking on a feature (let feature popups take precedence)
let featureClicked = false;
// For map 0, check all geoLayers; for others, check geoLayer
if (idx === 0 && Array.isArray(mapSections[0]?.geoLayers)) {
mapSections[0].geoLayers.forEach(gl => {
gl.eachLayer(layer => {
if (layer.getBounds && layer.getBounds().contains(e.latlng)) featureClicked = true;
});
});
} else if (mapSections[idx]?.geoLayer) {
mapSections[idx].geoLayer.eachLayer(layer => {
if (layer.getBounds && layer.getBounds().contains(e.latlng)) featureClicked = true;
});
}
if (featureClicked) return;
const lat = e.latlng.lat.toFixed(6);
const lng = e.latlng.lng.toFixed(6);
const popupContent = `<div style='font-size:1em;'>Lat: <b>${lat}</b><br>Lng: <b>${lng}</b><br><button id='copy-latlng-btn' style='margin-top:6px;padding:2px 10px;font-size:0.98em;cursor:pointer;'>Copy</button></div>`;
const popup = L.popup()
.setLatLng(e.latlng)
.setContent(popupContent)
.openOn(map);
setTimeout(() => {
const btn = document.getElementById('copy-latlng-btn');
if (btn) {
btn.onclick = function() {
navigator.clipboard.writeText(`${lat}, ${lng}`);
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy'; }, 1200);
};
}
}, 100);
});
// Add multi-select dropdown as a Leaflet control for map 0
if (idx === 0) {
const MultiLayerDropdown = L.Control.extend({
options: { position: 'topright' },
onAdd: function() {
const container = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
container.style.background = '#fff';
container.style.padding = '4px 8px';
container.style.margin = '6px 0 0 0';
container.style.borderRadius = '6px';
container.style.boxShadow = '0 2px 8px rgba(0,0,0,0.07)';
container.style.display = 'flex';
container.style.flexDirection = 'column';
container.style.alignItems = 'stretch';
const label = document.createElement('label');
label.textContent = 'Layers:';
label.style.fontWeight = 'bold';
label.style.fontSize = '0.98em';
label.style.marginBottom = '2px';
label.style.marginRight = '0';
container.appendChild(label);
const select = document.createElement('select');
select.id = 'multi-layer-select';
select.multiple = true;
select.size = Math.min(LAYER_OPTIONS.length, 5);
select.style.minWidth = '140px';
select.style.fontSize = '1em';
select.style.padding = '2px 6px';
select.style.border = '1.5px solid #bbb';
select.style.borderRadius = '4px';
select.style.background = '#fff';
select.style.marginBottom = '0';
LAYER_OPTIONS.forEach((opt, i) => {
const option = document.createElement('option');
option.value = i;
option.textContent = opt.label;
select.appendChild(option);
});
container.appendChild(select);
L.DomEvent.disableClickPropagation(container);
// Attach event listener here so it works after layout changes
setTimeout(() => {
const selectEl = document.getElementById('multi-layer-select');
if (selectEl) {
selectEl.addEventListener('change', function() {
const selected = Array.from(selectEl.selectedOptions).map(opt => parseInt(opt.value)).filter(v => !isNaN(v));
const ms0 = mapSections[0];
if (ms0 && ms0.map && typeof ms0.index === 'number' && ms0.index === 0) {
ms0.loadedLayers = selected;
ms0.geoLayers = ms0.geoLayers || [];
ms0.geoLayers.forEach(l => ms0.map.removeLayer(l));
ms0.geoLayers = [];
if (selected.length > 0) {
if (typeof window.loadLayersMultiMap0 === 'function') {
window.loadLayersMultiMap0(selected);
}
} else {
ms0.geoLayers = [];
}
}
});
}
}, 0);
return container;
}
});
map.addControl(new MultiLayerDropdown());
}
let geoLayers = [];
// For map 0, support multiple layers
function loadLayersMulti(selectedLayerIdxs) {
// Remove all previous layers
geoLayers.forEach(l => map.removeLayer(l));
geoLayers = [];
if (!selectedLayerIdxs || selectedLayerIdxs.length === 0) {
updateDebugStatus('No layer loaded. Please select one or more layers.');
return;
}
let loadedCount = 0;
selectedLayerIdxs.forEach(layerIdx => {
const opt = LAYER_OPTIONS[layerIdx];
updateDebugStatus(`Loading ${opt.label}...`);
fetch(opt.url)
.then(r => {
if (!r.ok) throw new Error(`HTTP error! status: ${r.status}`);
return r.json();
})
.then(data => {
if (!data || !data.features || data.features.length === 0) {
updateDebugStatus(`Warning: No features in ${opt.label}`);
L.popup()
.setLatLng(initialCenter)
.setContent(`<div style="color:orange">⚠️ No features found in ${opt.label}</div>`)
.openOn(map);
} else {
updateDebugStatus(`Loaded ${opt.label}: ${data.features.length} features`);
}
const geoLayer = L.geoJSON(data, {
style: { color: opt.color, weight: 2, fillOpacity: 0.1 },
onEachFeature: (feature, layer) => {
const title = opt.label;
let lat = '';
let lng = '';
if (feature.geometry && feature.geometry.type && feature.geometry.coordinates) {
if (feature.geometry.type === 'Point') {
lat = feature.geometry.coordinates[1];
lng = feature.geometry.coordinates[0];
} else if (layer.getBounds) {
const c = layer.getBounds().getCenter();
lat = c.lat;
lng = c.lng;
}
}
const content = createPopupContent(title, opt.color, feature.properties, lat, lng);
layer.bindPopup(content);
layer.on('popupopen', () => attachCopyButtonHandler(lat, lng));
layer.on('click', function(e) {
L.DomEvent.stopPropagation(e);
const latlng = e.latlng;
updateDebugStatus(`Clicked: ${feature.properties.ward_name || feature.properties.id || 'feature'}`);
mapSections.forEach((ms) => {
if (ms.map !== map) {
ms.map.fire('external-feature-click', { latlng });
}
});
});
}
}).addTo(map);
geoLayers.push(geoLayer);
loadedCount++;
if (loadedCount === selectedLayerIdxs.length) {
updateDebugStatus(`Loaded ${loadedCount} layer(s)`);
}
})
.catch(error => {
updateDebugStatus(`Error loading ${opt.label}`);
L.popup()
.setLatLng(initialCenter)
.setContent(`<div style=\"color:red\">❌ Error loading ${opt.label}:<br>${error.message}</div>`)
.openOn(map);
});
});
}
// For other maps, keep single-layer logic
let geoLayer = null;
function loadLayer(layerIdx) {
if (geoLayer) map.removeLayer(geoLayer);
if (layerIdx === undefined || layerIdx === null || isNaN(layerIdx)) {
updateDebugStatus('No layer loaded. Please select a layer from the dropdown to proceed.');
return;
}
const opt = LAYER_OPTIONS[layerIdx];
updateDebugStatus(`Loading ${opt.label}...`);
// Update loadedLayer for this mapSection
const thisMapIndex = mapSections.findIndex(ms => ms.map === map);
if (thisMapIndex >= 0) {
mapSections[thisMapIndex].loadedLayer = layerIdx;
}
fetch(opt.url)
.then(r => {
if (!r.ok) throw new Error(`HTTP error! status: ${r.status}`);
return r.json();
})
.then(data => {
if (!data || !data.features || data.features.length === 0) {
updateDebugStatus(`Warning: No features in ${opt.label}`);
L.popup()
.setLatLng(initialCenter)
.setContent(`<div style=\"color:orange\">⚠️ No features found in ${opt.label}</div>`)
.openOn(map);
} else {
updateDebugStatus(`Loaded ${opt.label}: ${data.features.length} features`);
}
geoLayer = L.geoJSON(data, {
style: { color: opt.color, weight: 2, fillOpacity: 0.1 },
onEachFeature: (feature, layer) => {
const title = opt.label;
let lat = '';
let lng = '';
if (feature.geometry && feature.geometry.type && feature.geometry.coordinates) {
if (feature.geometry.type === 'Point') {
lat = feature.geometry.coordinates[1];
lng = feature.geometry.coordinates[0];
} else if (layer.getBounds) {
const c = layer.getBounds().getCenter();
lat = c.lat;
lng = c.lng;
}
}
const content = createPopupContent(title, opt.color, feature.properties, lat, lng);
layer.bindPopup(content);
layer.on('popupopen', () => attachCopyButtonHandler(lat, lng));
layer.on('click', function(e) {
L.DomEvent.stopPropagation(e);
const latlng = e.latlng;
updateDebugStatus(`Clicked: ${feature.properties.ward_name || feature.properties.id || 'feature'}`);
mapSections.forEach((ms) => {
if (ms.map !== map) {
ms.map.fire('external-feature-click', { latlng });
}
});
});
}
}).addTo(map);
// Assign geoLayer to ms.geoLayer in mapSections for search/highlight
if (thisMapIndex >= 0) {
mapSections[thisMapIndex].geoLayer = geoLayer;
}
})
.catch(error => {
updateDebugStatus(`Error loading ${opt.label}`);
L.popup()
.setLatLng(initialCenter)
.setContent(`<div style=\"color:red\">❌ Error loading ${opt.label}:<br>${error.message}</div>`)
.openOn(map);
});
}
// Do not load any layer by default
updateDebugStatus('No layer loaded. Please select a layer from the dropdown to proceed.');
// Add dropdown as a Leaflet control (topright) for maps 1+
if (idx !== 0) {
const LayerDropdown = L.Control.extend({
options: { position: 'topright' },
onAdd: function() {
const container = L.DomUtil.create('div', 'leaflet-bar leaflet-control');
const select = L.DomUtil.create('select', '', container);
select.style.margin = '4px';
select.style.padding = '2px 6px';
select.style.fontSize = '1em';
select.id = `layer-select-${idx}`;
// Add 'Select...' option at the top
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = 'Select...';
placeholder.disabled = true;
placeholder.selected = true;
select.appendChild(placeholder);
LAYER_OPTIONS.forEach((opt, i) => {
const option = document.createElement('option');
option.value = i;
option.textContent = opt.label;
select.appendChild(option);
});
L.DomEvent.disableClickPropagation(container);
L.DomEvent.on(select, 'change', function(e) {
const layerIdx = parseInt(e.target.value);
if (isNaN(layerIdx)) return;
loadLayer(layerIdx);
});
return container;
}
});
map.addControl(new LayerDropdown());
}
// Store map with additional properties
if (idx === 0) {
mapSections.push({
map,
geoLayers, // Array of layers for multi
index: idx,
loadedLayers: [] // Track which layers are loaded
});
} else {
mapSections.push({
map,
geoLayer, // Single layer for others
index: idx,
loadedLayer: 0 // Track which layer is loaded
});
}
// Update layout now that mapSections/DOM have changed
updateGridLayout();
// (removed: now handled in addMapSection for map 0)
// Expose the multi-layer loader for map 0
window.loadLayersMultiMap0 = function(selectedLayerIdxs) {
if (!mapSections[0]) return;
const ms0 = mapSections[0];
if (!ms0.map) return;
// Remove all previous layers
ms0.geoLayers.forEach(l => ms0.map.removeLayer(l));
ms0.geoLayers = [];
if (!selectedLayerIdxs || selectedLayerIdxs.length === 0) {
const debugEl = document.getElementById('debug-status-0');
if (debugEl) debugEl.innerHTML = 'Map 0: No layer loaded. Please select one or more layers.';
return;
}
let loadedCount = 0;
selectedLayerIdxs.forEach(layerIdx => {
const opt = LAYER_OPTIONS[layerIdx];
fetch(opt.url)
.then(r => { if (!r.ok) throw new Error(`HTTP error! status: ${r.status}`); return r.json(); })
.then(data => {
const geoLayer = L.geoJSON(data, {
style: { color: opt.color, weight: 2, fillOpacity: 0.1 },
onEachFeature: (feature, layer) => {
const title = opt.label;
let lat = '';
let lng = '';
if (feature.geometry && feature.geometry.type && feature.geometry.coordinates) {
if (feature.geometry.type === 'Point') {
lat = feature.geometry.coordinates[1];
lng = feature.geometry.coordinates[0];
} else if (layer.getBounds) {
const c = layer.getBounds().getCenter();
lat = c.lat;
lng = c.lng;
}
}
const content = createPopupContent(title, opt.color, feature.properties, lat, lng);
layer.bindPopup(content);
layer.on('popupopen', () => attachCopyButtonHandler(lat, lng));
layer.on('click', function(e) {
L.DomEvent.stopPropagation(e);