-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1000 lines (870 loc) · 35 KB
/
index.html
File metadata and controls
1000 lines (870 loc) · 35 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" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hex Picker with Zones</title>
<!-- Font Awesome CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<!-- Leaflet Draw CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css" />
<style>
html,
body,
#map {
width: 100%;
height: 100%;
margin: 0;
}
/* ------------------ Card Layout ------------------ */
.card {
position: absolute;
top: 12px;
right: 12px;
z-index: 1000;
background: #ffffff;
border: 1px solid #e1e1e1;
border-radius: 10px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
padding: 16px 18px;
width: 320px;
display: flex;
flex-direction: column;
gap: 12px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.controls {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.card select,
.card button {
padding: 8px 10px;
font-size: 14px;
border-radius: 6px;
border: 1px solid #ccc;
background: #f9f9f9;
cursor: pointer;
transition: background 0.15s;
}
.card button {
background: #007bff;
color: #ffffff;
border: none;
}
.card button:hover:not(:disabled) {
background: #0069d9;
}
.card button:disabled {
background: #d6d6d6;
cursor: not-allowed;
}
#hexagonCounter {
font-size: 14px;
font-weight: 500;
}
/* ------------------ Zones list ------------------ */
#zonesContainer {
max-height: 240px;
overflow-y: auto;
border: 1px solid #f1f1f1;
padding: 6px 4px;
border-radius: 6px;
}
.zone-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 4px;
border-bottom: 1px solid #f3f3f3;
}
.zone-item:last-child {
border-bottom: none;
}
.zone-left {
display: flex;
align-items: flex-start;
gap: 8px;
}
.color-swatch {
width: 16px;
height: 16px;
border-radius: 3px;
border: 1px solid #979797;
cursor: pointer;
flex: 0 0 16px;
margin-top: 2px;
}
.zone-name {
font-weight: 600;
}
.zone-meta {
font-size: 12px;
color: #5e5e5e;
}
.action-btns {
display: flex;
flex-direction: row;
gap: 6px;
align-items: center;
}
.action-btns>button {
padding: 6px;
line-height: 1;
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 30px;
min-height: 30px;
border-radius: 4px;
border: none;
transition: background-color 0.15s ease;
}
.action-btns>button i {
font-size: 14px;
color: inherit;
}
.action-btns>button:disabled {
opacity: .65;
}
.edit-btn {
background: #17a2b8;
color: #fff;
}
.edit-btn:hover:not(:disabled) {
background: #138496;
}
.edit-active {
background: #ffc107 !important;
color: #000 !important;
padding: 6px 10px !important;
font-size: 13px;
}
.edit-active i {
margin-right: 5px;
}
.delete-btn {
background: #dc3545;
color: #fff;
}
.delete-btn:hover:not(:disabled) {
background: #c82333;
}
.locate-btn {
background: #6f42c1;
color: #fff;
}
.locate-btn:hover:not(:disabled) {
background: #59309f;
}
/* ------------------ Zones Summary ------------------ */
#zonesSummary {
font-size: 13px;
color: #333;
padding-top: 8px;
margin-top: 4px;
border-top: 1px solid #eaeaea;
line-height: 1.5;
}
#zonesSummary strong {
color: #111;
}
.rename-btn {
background: #6c757d;
color: #fff;
}
.rename-btn:hover:not(:disabled) {
background: #5a6268;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- ------------- Side Card ------------- -->
<div class="card">
<div class="controls">
<select id="resolutionSelect"></select>
<button id="drawButton">Draw Polygon</button>
<button id="clearButton" disabled>Clear Selection</button>
<button id="createZoneButton" disabled>Create Zone</button>
<button id="finishEditButton" style="display:none; background:#28a745">Finish Editing</button>
<button id="copyIdsButton" disabled>Copy Cell IDs</button>
<button id="copyGeoButton" disabled>Copy GeoJSON</button>
<button id="exportGeoButton" disabled>Export GeoJSON</button>
<button id="importGeoButton">Import GeoJSON</button>
</div>
<input type="file" id="geojsonFile" accept=".geojson,.json" style="display:none;">
<div id="hexagonCounter">Selected Hexagons: 0</div>
<hr />
<strong>Zones</strong>
<div id="zonesContainer"></div>
<div id="zonesSummary"></div>
</div>
<!-- ------------------- Your app as a browser ES module ------------------- -->
<script type="module">
// Use ESM versions from a CDN. We pin Leaflet for the Draw plugin with ?deps=.
import * as L from "https://esm.sh/leaflet@1.9.4";
import "https://esm.sh/leaflet-draw@1.0.4?deps=leaflet@1.9.4";
import * as h3 from "https://esm.sh/h3-js@4.1.0";
/*************************************************
* Globals & helpers
*************************************************/
const DEFAULT_RESOLUTION = 8;
const MAP_CENTER = [32.85, 13.1913];
const HEX_COLOR_REGEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
let h3Resolution = DEFAULT_RESOLUTION;
const map = L.map("map").setView(MAP_CENTER, 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "© OpenStreetMap contributors",
}).addTo(map);
// Layers
const cellsLayer = L.layerGroup().addTo(map);
const zoneOutlinesLayer = L.layerGroup().addTo(map);
// Data stores
let drawnCells = new Set();
let cellPolygons = {};
let selectedCells = new Set();
let zones = [];
let hexToZone = {};
let editingZoneId = null;
let zoneCounter = 0;
// -------- Utility --------
const fmtInt = (v) => v.toLocaleString(undefined, { maximumFractionDigits: 0 });
const computeArea = (hexSet) => {
let total = 0;
hexSet.forEach((h) => (total += h3.cellArea(h, "m2")));
return total;
};
const isValidHexColor = (c) => HEX_COLOR_REGEX.test(c);
/*************************************************
* DOM refs
*************************************************/
const drawButton = document.getElementById("drawButton");
const clearButton = document.getElementById("clearButton");
const createZoneButton = document.getElementById("createZoneButton");
const finishEditButton = document.getElementById("finishEditButton");
const copyIdsButton = document.getElementById("copyIdsButton");
const copyGeoButton = document.getElementById("copyGeoButton");
const resolutionSelect = document.getElementById("resolutionSelect");
const hexagonCounter = document.getElementById("hexagonCounter");
const zonesContainer = document.getElementById("zonesContainer");
const exportGeoButton = document.getElementById("exportGeoButton");
const importGeoButton = document.getElementById("importGeoButton");
const geojsonFileInput = document.getElementById("geojsonFile");
const zonesSummaryEl = document.getElementById("zonesSummary");
// Populate resolution dropdown
for (let r = 0; r <= 15; r++) {
const opt = document.createElement("option");
opt.value = r.toString();
opt.textContent = `Resolution ${r}`;
if (r === DEFAULT_RESOLUTION) opt.selected = true;
resolutionSelect.appendChild(opt);
}
/*************************************************
* Utility UI functions
*************************************************/
function updateHexagonCounter() {
hexagonCounter.textContent = `Selected Hexagons: ${selectedCells.size}`;
clearButton.disabled = selectedCells.size === 0;
createZoneButton.disabled = selectedCells.size === 0;
}
function updateCopyButtons() {
const disabled = zones.length === 0;
copyIdsButton.disabled = disabled;
copyGeoButton.disabled = disabled;
exportGeoButton.disabled = disabled;
}
function updateZonesSummary() {
if (zones.length === 0) {
zonesSummaryEl.innerHTML = "";
zonesSummaryEl.style.display = "none";
return;
}
let totalHexagons = 0;
let totalArea = 0;
zones.forEach(zone => {
totalHexagons += zone.hexagons.size;
totalArea += zone.area;
});
zonesSummaryEl.innerHTML = `
<strong>Total Zones:</strong> ${zones.length}<br>
<strong>Total Hexagons:</strong> ${fmtInt(totalHexagons)}<br>
<strong>Total Area:</strong> ${fmtInt(totalArea)} m²
`;
zonesSummaryEl.style.display = "block";
}
function renderZonesList() {
zonesContainer.innerHTML = "";
zones.forEach((z) => {
const item = document.createElement("div");
item.className = "zone-item";
const left = document.createElement("div");
left.className = "zone-left";
const swatch = document.createElement("span");
swatch.className = "color-swatch";
swatch.style.background = z.color;
swatch.title = "Click to change color";
swatch.addEventListener("click", () => changeZoneColor(z.id));
const nameWrap = document.createElement("div");
const nameSpan = document.createElement("div");
nameSpan.textContent = z.name;
nameSpan.className = "zone-name";
const metaSpan = document.createElement("div");
metaSpan.textContent = `${z.hexagons.size} hex • ${fmtInt(z.area)} m²`;
metaSpan.className = "zone-meta";
nameWrap.appendChild(nameSpan);
nameWrap.appendChild(metaSpan);
left.appendChild(swatch);
left.appendChild(nameWrap);
const actions = document.createElement("div");
actions.className = "action-btns";
// Edit button
const editBtn = document.createElement("button");
editBtn.className = "edit-btn";
if (editingZoneId === z.id) {
editBtn.innerHTML = '<i class="fas fa-pencil-alt"></i> Editing…';
editBtn.classList.add("edit-active");
} else {
editBtn.innerHTML = '<i class="fas fa-pencil-alt"></i>';
editBtn.title = "Edit Zone";
}
editBtn.disabled = editingZoneId !== null && editingZoneId !== z.id;
editBtn.addEventListener("click", () => toggleEditZone(z.id));
// Rename button
const renameBtn = document.createElement("button");
renameBtn.className = "rename-btn";
renameBtn.innerHTML = '<i class="fas fa-font"></i>';
renameBtn.title = "Rename Zone";
renameBtn.disabled = editingZoneId !== null && editingZoneId !== z.id;
renameBtn.addEventListener("click", () => renameZone(z.id));
// Center/locate button
const locateBtn = document.createElement("button");
locateBtn.className = "locate-btn";
locateBtn.innerHTML = '<i class="fas fa-crosshairs"></i>';
locateBtn.title = "Center map on zone";
locateBtn.disabled = editingZoneId !== null && editingZoneId !== z.id;
locateBtn.addEventListener("click", () => zoomToZone(z.id));
// Delete button
const deleteBtn = document.createElement("button");
deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
deleteBtn.title = "Delete Zone";
deleteBtn.className = "delete-btn";
deleteBtn.disabled = editingZoneId !== null;
deleteBtn.addEventListener("click", () => deleteZone(z.id));
actions.appendChild(editBtn);
actions.appendChild(renameBtn);
actions.appendChild(locateBtn);
actions.appendChild(deleteBtn);
item.appendChild(left);
item.appendChild(actions);
zonesContainer.appendChild(item);
});
updateCopyButtons();
updateZonesSummary();
}
/*************************************************
* Grid drawing
*************************************************/
function drawH3Cells() {
const bounds = map.getBounds();
const nw = bounds.getNorthWest();
const se = bounds.getSouthEast();
const hexagonsToDraw = h3.polygonToCells(
[
[nw.lat, nw.lng],
[se.lat, nw.lng],
[se.lat, se.lng],
[nw.lat, se.lng],
],
h3Resolution,
false
);
hexagonsToDraw.forEach((hex) => {
if (drawnCells.has(hex)) return;
const coords = h3.cellToBoundary(hex).map(([lat, lng]) => [lat, lng]);
const polygon = L.polygon(coords, { color: "blue", weight: 1, fillOpacity: 0 });
polygon.h3Index = hex;
if (hexToZone[hex] !== undefined) {
const zone = zones.find((z) => z.id === hexToZone[hex]);
if (zone) {
applyZoneStyle(polygon, zone);
polygon.inZone = true;
}
}
polygon.on("mouseover", function () {
if (this.inZone || editingZoneId !== null) return;
if (!selectedCells.has(this.h3Index)) this.setStyle({ fillOpacity: 0.25 });
});
polygon.on("mouseout", function () {
if (this.inZone || editingZoneId !== null) return;
if (!selectedCells.has(this.h3Index)) this.setStyle({ fillOpacity: 0 });
});
polygon.on("click", function () {
const hex = this.h3Index;
if (editingZoneId !== null) { handleEditingClick(hex, this); return; }
if (hexToZone[hex] !== undefined) {
alert(`Hexagon already in zone "${zones.find((z) => z.id === hexToZone[hex]).name}"`);
return;
}
toggleSelection(hex, this);
});
cellPolygons[hex] = polygon;
cellsLayer.addLayer(polygon);
drawnCells.add(hex);
});
}
map.on("moveend", drawH3Cells);
drawH3Cells();
/*************************************************
* Selection helpers
*************************************************/
function toggleSelection(hex, polygon) {
if (selectedCells.has(hex)) {
selectedCells.delete(hex);
polygon.setStyle({ fillOpacity: 0 });
} else {
selectedCells.add(hex);
polygon.setStyle({ fillOpacity: 0.5 });
}
updateHexagonCounter();
}
function selectHex(hex) {
if (selectedCells.has(hex)) return;
const polygon = cellPolygons[hex];
if (!polygon) return;
selectedCells.add(hex);
polygon.setStyle({ fillOpacity: 0.5 });
updateHexagonCounter();
}
/*************************************************
* Leaflet‑draw selection polygon
*************************************************/
const drawControl = new L.Control.Draw({
draw: { polygon: true, polyline: false, rectangle: false, circle: false, marker: false, circlemarker: false }
});
let isDrawing = false;
drawButton.addEventListener("click", () => {
if (isDrawing) {
map.removeControl(drawControl);
drawButton.textContent = "Draw Polygon";
isDrawing = false;
} else {
if (editingZoneId !== null) return;
map.addControl(drawControl);
drawButton.textContent = "Cancel Drawing";
isDrawing = true;
}
});
map.on("draw:created", (e) => {
const layer = e.layer;
const poly = layer.toGeoJSON().geometry.coordinates[0].map(([lng, lat]) => [lat, lng]);
const hexagons = h3.polygonToCells(poly, h3Resolution, false);
hexagons.forEach((h) => { if (hexToZone[h] === undefined) selectHex(h); });
map.removeControl(drawControl);
drawButton.textContent = "Draw Polygon";
isDrawing = false;
});
/*************************************************
* Zone functions
*************************************************/
createZoneButton.addEventListener("click", () => {
if (selectedCells.size === 0) return;
let name;
while (true) {
name = prompt("Zone name:");
if (name === null) return;
name = name.trim();
if (name === "") { alert("Zone name cannot be empty. Please enter a name."); continue; }
if (zones.some((z) => z.name.toLowerCase() === name.toLowerCase())) { alert("Zone name must be unique. Please try a different name."); continue; }
break;
}
let color;
while (true) {
color = prompt("Zone color (#RRGGBB or #RGB):", "#ff0000");
if (color === null) return;
if (!isValidHexColor(color)) { alert("Color must be a valid hex code starting with # (e.g., #ff0000 or #f00)."); continue; }
if (zones.some((z) => z.color.toLowerCase() === color.toLowerCase())) { alert("Zone color must be unique. Please choose a different color."); continue; }
break;
}
const overlap = Array.from(selectedCells).filter((h) => hexToZone[h] !== undefined);
if (overlap.length) { alert("Some selected hexagons are already assigned to zones."); return; }
const area = computeArea(selectedCells);
const zone = { id: zoneCounter++, name, color, hexagons: new Set(selectedCells), area, outlinePolys: [] };
zones.push(zone);
zone.hexagons.forEach((hex) => {
hexToZone[hex] = zone.id;
const poly = cellPolygons[hex];
if (poly) { applyZoneStyle(poly, zone); poly.inZone = true; }
});
drawZoneOutline(zone);
selectedCells.clear();
updateHexagonCounter();
renderZonesList();
});
clearButton.addEventListener("click", () => {
selectedCells.forEach((hex) => { const poly = cellPolygons[hex]; if (poly) poly.setStyle({ fillOpacity: 0 }); });
selectedCells.clear();
updateHexagonCounter();
});
function applyZoneStyle(polygon, zone) {
polygon.setStyle({ fillOpacity: 0.5, fillColor: zone.color, weight: 0 });
}
function drawZoneOutline(zone) {
if (zone.outlinePolys?.length) zone.outlinePolys.forEach((p) => zoneOutlinesLayer.removeLayer(p));
zone.outlinePolys = [];
const multiLngLat = h3.cellsToMultiPolygon(Array.from(zone.hexagons), true);
multiLngLat.forEach((polyLngLat) => {
const latlngs = polyLngLat.map((ringLngLat) => ringLngLat.map(([lng, lat]) => [lat, lng]));
const outline = L.polygon(latlngs, { color: zone.color, weight: 3, fillOpacity: 0, interactive: false });
zoneOutlinesLayer.addLayer(outline);
zone.outlinePolys.push(outline);
});
}
function changeZoneColor(zoneId) {
const zone = zones.find((z) => z.id === zoneId);
if (!zone) return;
let newColor;
while (true) {
newColor = prompt("New color (#RRGGBB or #RGB):", zone.color);
if (newColor === null) return;
if (newColor.toLowerCase() === zone.color.toLowerCase()) return;
if (!isValidHexColor(newColor)) { alert("Color must be a valid hex code starting with # (e.g., #ff0000 or #f00)."); continue; }
if (zones.some((z_other) => z_other.id !== zoneId && z_other.color.toLowerCase() === newColor.toLowerCase())) { alert("This color is already used by another zone. Please choose a unique color."); continue; }
break;
}
zone.color = newColor;
zone.hexagons.forEach((hex) => { const poly = cellPolygons[hex]; if (poly) applyZoneStyle(poly, zone); });
drawZoneOutline(zone);
renderZonesList();
}
// Fit map to a zone's full extent (N/S/E/W extremes)
function zoomToZone(zoneId) {
const zone = zones.find((z) => z.id === zoneId);
if (!zone) return;
// Ensure outlines exist for bounds calculation
if (!zone.outlinePolys || zone.outlinePolys.length === 0) {
drawZoneOutline(zone);
}
let combinedBounds = null;
if (zone.outlinePolys && zone.outlinePolys.length) {
zone.outlinePolys.forEach((poly) => {
const b = poly.getBounds();
if (!combinedBounds) {
combinedBounds = L.latLngBounds(b.getSouthWest(), b.getNorthEast());
} else {
combinedBounds.extend(b);
}
});
} else {
// Fallback: compute bounds from cell boundaries
const latlngs = [];
zone.hexagons.forEach((hex) => {
const boundary = h3.cellToBoundary(hex);
boundary.forEach(([lat, lng]) => latlngs.push([lat, lng]));
});
if (latlngs.length) {
combinedBounds = L.latLngBounds(latlngs.map(([lat, lng]) => L.latLng(lat, lng)));
}
}
if (combinedBounds) {
map.fitBounds(combinedBounds, { padding: [40, 40] });
}
}
function toggleEditZone(zoneId) {
if (editingZoneId === zoneId) { finishEditing(); return; }
if (editingZoneId !== null) return;
editingZoneId = zoneId;
drawButton.disabled = true;
resolutionSelect.disabled = true;
createZoneButton.disabled = true;
importGeoButton.disabled = true;
finishEditButton.style.display = "block";
renderZonesList();
}
finishEditButton.addEventListener("click", finishEditing);
function finishEditing() {
editingZoneId = null;
drawButton.disabled = false;
resolutionSelect.disabled = false;
createZoneButton.disabled = selectedCells.size === 0;
importGeoButton.disabled = false;
finishEditButton.style.display = "none";
renderZonesList();
}
function handleEditingClick(hex, polygon) {
const zone = zones.find((z) => z.id === editingZoneId);
if (!zone) return;
const hexArea = h3.cellArea(hex, "m2");
if (zone.hexagons.has(hex)) {
zone.hexagons.delete(hex);
zone.area -= hexArea;
delete hexToZone[hex];
polygon.inZone = false;
polygon.setStyle({ fillOpacity: 0, color: "blue", weight: 1 });
} else {
if (hexToZone[hex] !== undefined) { alert("Hexagon already belongs to another zone."); return; }
zone.hexagons.add(hex);
zone.area += hexArea;
hexToZone[hex] = zone.id;
polygon.inZone = true;
applyZoneStyle(polygon, zone);
}
drawZoneOutline(zone);
renderZonesList();
}
function deleteZone(zoneId) {
const idx = zones.findIndex((z) => z.id === zoneId);
if (idx === -1) return;
const zone = zones[idx];
if (!confirm(`Delete zone "${zone.name}"? This cannot be undone.`)) return;
if (editingZoneId !== null) { alert("Finish editing before deleting a zone."); return; }
zone.outlinePolys?.forEach((p) => zoneOutlinesLayer.removeLayer(p));
zone.hexagons.forEach((hex) => {
delete hexToZone[hex];
const poly = cellPolygons[hex];
if (poly) { poly.inZone = false; poly.setStyle({ fillOpacity: 0, color: "blue", weight: 1 }); }
});
zones.splice(idx, 1);
renderZonesList();
}
/*************************************************
* Copy & Export buttons
*************************************************/
function getGeoJSONForAllZones() {
const features = zones.map((z) => {
const multiLngLat = h3.cellsToMultiPolygon(Array.from(z.hexagons), true);
return {
type: "Feature",
geometry: { type: "MultiPolygon", coordinates: multiLngLat },
properties: {
zone_name: z.name,
zone_color: z.color,
hex_count: z.hexagons.size,
area_m2: Math.round(z.area),
h3_resolution: h3Resolution,
},
};
});
return { type: "FeatureCollection", features };
}
copyIdsButton.addEventListener("click", () => {
const payload = zones.map((z) => ({
zone_name: z.name,
zone_color: z.color,
hex_count: z.hexagons.size,
area_m2: Math.round(z.area),
zone_cells: Array.from(z.hexagons),
}));
navigator.clipboard.writeText(JSON.stringify(payload, null, 2))
.then(() => alert("Zone cell IDs copied!"));
});
copyGeoButton.addEventListener("click", () => {
const geojson = getGeoJSONForAllZones();
navigator.clipboard.writeText(JSON.stringify(geojson, null, 2))
.then(() => alert("GeoJSON copied!"));
});
exportGeoButton.addEventListener("click", () => {
if (zones.length === 0) return;
const geojson = getGeoJSONForAllZones();
const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = "zones.geojson";
document.body.appendChild(a); a.click();
document.body.removeChild(a); URL.revokeObjectURL(url);
});
/*************************************************
* Import GeoJSON
*************************************************/
let genericZoneNameCounter = 1;
const defaultColors = ["#E6194B", "#3CB44B", "#FFE119", "#4363D8", "#F58231", "#911EB4", "#46F0F0", "#F032E6", "#BCF60C", "#FABEBE", "#008080", "#E6BEFF", "#9A6324", "#FFFAC8", "#800000", "#AAFFC3", "#808000", "#FFD8B1", "#000075", "#808080"];
let defaultColorIndex = 0;
function generateUniqueZoneName(currentGlobalZones, tempNewZonesList) {
let name;
do {
name = `Zone ${genericZoneNameCounter++}`;
} while (currentGlobalZones.some(z => z.name.toLowerCase() === name.toLowerCase()) ||
tempNewZonesList.some(nz => nz.name.toLowerCase() === name.toLowerCase()));
return name;
}
function generateUniqueZoneColor(currentGlobalZones, tempNewZonesList) {
let color; let attempts = 0;
const initialIndex = defaultColorIndex;
do {
color = defaultColors[defaultColorIndex % defaultColors.length];
defaultColorIndex++; attempts++;
if (attempts > defaultColors.length && defaultColorIndex % defaultColors.length === initialIndex % defaultColors.length) break;
} while ((currentGlobalZones.some(z => z.color.toLowerCase() === color.toLowerCase()) ||
tempNewZonesList.some(nz => nz.color.toLowerCase() === color.toLowerCase())) && attempts < defaultColors.length * 2);
if (currentGlobalZones.some(z => z.color.toLowerCase() === color.toLowerCase()) ||
tempNewZonesList.some(nz => nz.color.toLowerCase() === color.toLowerCase())) {
do { color = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0'); }
while (currentGlobalZones.some(z => z.color.toLowerCase() === color.toLowerCase()) ||
tempNewZonesList.some(nz => nz.color.toLowerCase() === color.toLowerCase()));
}
return color;
}
importGeoButton.addEventListener("click", () => {
if (editingZoneId !== null) { alert("Please finish editing the current zone before importing."); return; }
geojsonFileInput.click();
});
geojsonFileInput.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
const geojsonData = JSON.parse(e.target.result);
if (geojsonData.type !== "FeatureCollection" || !Array.isArray(geojsonData.features)) throw new Error("Invalid GeoJSON: Must be a FeatureCollection with a 'features' array.");
if (geojsonData.features.length === 0) { alert("No features found in the GeoJSON file."); event.target.value = null; return; }
const importResolution = geojsonData.features[0]?.properties?.h3_resolution;
if (importResolution !== undefined && importResolution !== h3Resolution) {
if (!confirm(`The imported GeoJSON was created with H3 resolution ${importResolution}, but your current resolution is ${h3Resolution}. Cells will be generated using resolution ${h3Resolution}. This may lead to different results. Continue?`)) {
event.target.value = null; return;
}
}
if (zones.length > 0) {
if (!confirm("Importing new GeoJSON will clear all existing zones. Continue?")) { event.target.value = null; return; }
clearAllZones();
if (selectedCells.size) clearButton.click();
} else {
genericZoneNameCounter = 1; defaultColorIndex = 0;
}
const importedZonesBatch = [];
let importedCellCount = 0;
for (const feature of geojsonData.features) {
if (feature.type !== "Feature" || !feature.geometry || feature.geometry.type !== "MultiPolygon") { console.warn("Skipping invalid feature:", feature); continue; }
let zoneName = feature.properties?.zone_name;
let zoneColor = feature.properties?.zone_color;
if (!zoneName || String(zoneName).trim() === "") {
zoneName = generateUniqueZoneName(zones, importedZonesBatch);
} else {
zoneName = String(zoneName).trim();
if (zones.some(z => z.name.toLowerCase() === zoneName.toLowerCase()) ||
importedZonesBatch.some(nz => nz.name.toLowerCase() === zoneName.toLowerCase())) {
console.warn(`Zone name "${zoneName}" from file already exists or is duplicated. Assigning a generic name.`);
zoneName = generateUniqueZoneName(zones, importedZonesBatch);
}
}
if (!zoneColor || !isValidHexColor(zoneColor)) {
if (zoneColor) console.warn(`Invalid color "${zoneColor}" for zone "${zoneName}". Assigning default.`);
zoneColor = generateUniqueZoneColor(zones, importedZonesBatch);
} else {
if (zones.some(z => z.color.toLowerCase() === zoneColor.toLowerCase()) ||
importedZonesBatch.some(nz => nz.color.toLowerCase() === zoneColor.toLowerCase())) {
console.warn(`Zone color "${zoneColor}" for zone "${zoneName}" already exists or is duplicated. Assigning new default.`);
zoneColor = generateUniqueZoneColor(zones, importedZonesBatch);
}
}
const zoneH3Cells = new Set();
for (const polygonGeoJsonCoords of feature.geometry.coordinates) {
if (polygonGeoJsonCoords && polygonGeoJsonCoords.length > 0 && polygonGeoJsonCoords[0].length >= 3) {
try {
const cellsFromPolygon = h3.polygonToCells(polygonGeoJsonCoords, h3Resolution, true);
cellsFromPolygon.forEach(cell => {
if (hexToZone[cell] !== undefined) {
const existingGlobalZone = zones.find(z => z.id === hexToZone[cell]);
console.warn(`Hex ${cell} for "${zoneName}" already in existing zone "${existingGlobalZone?.name}". Skipping cell.`);
} else {
let cellInBatch = false;
for (const bz of importedZonesBatch) {
if (bz.hexagons.has(cell)) {
console.warn(`Hex ${cell} for "${zoneName}" already in another new zone "${bz.name}" from this import. Skipping cell.`);
cellInBatch = true; break;
}
}
if (!cellInBatch) zoneH3Cells.add(cell);
}
});
} catch (h3Error) {
console.error(`Error converting polygon to H3 cells for zone "${zoneName}":`, h3Error, "Polygon data:", polygonGeoJsonCoords);
}
} else {
console.warn(`Skipping malformed polygon within MultiPolygon for zone "${zoneName}".`);
}
}
if (zoneH3Cells.size > 0) {
importedZonesBatch.push({ id: -1, name: zoneName, color: zoneColor, hexagons: zoneH3Cells, area: computeArea(zoneH3Cells), outlinePolys: [] });
importedCellCount += zoneH3Cells.size;
} else {
console.warn(`No valid, non-overlapping H3 cells generated for zone "${zoneName}". It might be too small, outside map, or entirely overlapping.`);
}
}
importedZonesBatch.forEach(newZoneData => {
newZoneData.id = zoneCounter++;
zones.push(newZoneData);
newZoneData.hexagons.forEach(hex => { hexToZone[hex] = newZoneData.id; });
});
if (importedZonesBatch.length > 0) {
redrawGrid();
renderZonesList();
alert(`Successfully imported ${importedZonesBatch.length} zone(s) with a total of ${importedCellCount} unique cells.`);
} else {
alert("Import complete, but no new zones were added. Check console for details if features were expected.");
}
} catch (error) {
console.error("Error importing GeoJSON:", error);
alert(`Error importing GeoJSON: ${error.message}`);
} finally {
event.target.value = null;
}
};
reader.onerror = () => { alert("Error reading file."); event.target.value = null; };
reader.readAsText(file);
});
/*************************************************
* Resolution change & redraw helpers
*************************************************/
resolutionSelect.addEventListener("change", function () {
if (zones.length && !confirm("Changing resolution will remove all zones and selections. Continue?")) {
this.value = h3Resolution; return;
}
clearAllZones();
if (selectedCells.size) clearButton.click();
h3Resolution = parseInt(this.value);
redrawGrid();
});
function clearAllZones() {
if (editingZoneId !== null) finishEditing();
zones.forEach((z) => { z.outlinePolys?.forEach((p) => zoneOutlinesLayer.removeLayer(p)); });
zones = []; hexToZone = {};
renderZonesList();
updateCopyButtons();
genericZoneNameCounter = 1;
defaultColorIndex = 0;
}
function redrawGrid() {
cellsLayer.clearLayers();
zoneOutlinesLayer.clearLayers();
drawnCells.clear();
cellPolygons = {};
drawH3Cells();
zones.forEach(drawZoneOutline);
}
/*************************************************
* Rename zone
*************************************************/
function renameZone(zoneId) {
const zone = zones.find(z => z.id === zoneId);
if (!zone) return;
let newName;
while (true) {
newName = prompt("New zone name:", zone.name);
if (newName === null) return;
newName = newName.trim();
if (newName === "") { alert("Name cannot be empty."); continue; }
if (zones.some(z => z.id !== zoneId && z.name.toLowerCase() === newName.toLowerCase())) { alert("Name must be unique."); continue; }
break;
}
zone.name = newName;
renderZonesList();
}
// Initial UI setup
updateCopyButtons();
renderZonesList();
</script>
</body>
</html>