aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/components/ParkMap.astro
blob: 3a208dbfcc6665ed6c8ce09c5b3c62dd232c7461 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
---
// 小平市の公園ポリゴン(OpenStreetMap)を地図上に色塗り表示する。
// 一覧と一致した公園は赤、一致しない公園は薄い赤で表示する。
---

<div class="park-map-wrap">
  <div
    id="park-map"
    class="park-map"
    role="region"
    aria-label="小平市の公園の位置(OpenStreetMap)"
  ></div>
  <p class="park-map-locate-status" data-locate-status hidden></p>
</div>

<style>
  .park-map-wrap {
    position: relative;
    z-index: 11;
    margin: 1rem 0 1.5rem;
  }
  .park-map {
    height: 480px;
    width: 100%;
    border: 1px solid var(--sl-color-gray-5);
    border-radius: 8px;
  }
  .park-map:fullscreen,
  .park-map:-webkit-full-screen {
    height: 100vh !important;
    width: 100vw !important;
    border: 0;
    border-radius: 0;
  }
  .park-map.is-maximized {
    position: fixed !important;
    inset: 0 !important;
    width: auto !important;
    height: auto !important;
    max-width: none !important;
    max-height: none !important;
    margin: 0 !important;
    border: 0 !important;
    border-radius: 0 !important;
    transform: none !important;
    z-index: 2147483000 !important;
  }
  :global(body.park-map-maximized) {
    overflow: hidden;
  }
  :global(.park-map-filter-panel) {
    position: absolute;
    top: 10px;
    left: 55px;
    right: 55px;
    z-index: 1000;
    max-height: 62vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: var(--sl-color-bg, #fff);
    color: var(--sl-color-text, #1e293b);
    border: 1px solid var(--sl-color-gray-5, #cbd5e1);
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
  }
  :global(.park-map-filter-toggle) {
    flex: none;
    padding: 0.4rem 0.6rem;
    border: 0;
    border-bottom: 1px solid var(--sl-color-gray-5, #cbd5e1);
    background: transparent;
    color: inherit;
    font: inherit;
    font-size: 0.85rem;
    font-weight: 700;
    text-align: left;
    cursor: pointer;
  }
  :global(.park-map-filter-body) {
    overflow: auto;
    padding: 0.5rem;
  }
  :global(.park-map-filter-body .parks-controls) {
    margin: 0;
  }
  :global(.park-map-filter-body .parks-disclaimer) {
    margin: 0.3rem 0 0;
  }
  :global(.park-map-filter-status) {
    display: inline-block;
    margin-left: 0.3rem;
    padding: 0 0.35rem;
    border-radius: 999px;
    background: #1b5e20;
    color: #fff;
    font-size: 0.7rem;
    font-weight: 700;
  }
  :global(.park-map-filter-footer) {
    flex: none;
    display: flex;
    gap: 0.5rem;
    align-items: center;
    justify-content: space-between;
    padding: 0.35rem 0.6rem;
    border-top: 1px solid var(--sl-color-gray-5, #cbd5e1);
    font-size: 0.72rem;
    color: var(--sl-color-gray-2, #666);
  }
  :global(.park-map-filter-close) {
    flex: none;
    padding: 0.25rem 0.8rem;
    border: 1px solid var(--sl-color-gray-5, #cbd5e1);
    border-radius: 999px;
    background: transparent;
    color: inherit;
    font: inherit;
    font-size: 0.78rem;
    cursor: pointer;
  }
  :global(.park-popup-row) {
    display: flex;
    gap: 0.35rem;
    align-items: flex-start;
    font-size: 0.78rem;
    margin-top: 0.1rem;
  }
  :global(.park-popup-ico) {
    position: relative;
    flex: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    width: 18px;
    height: 18px;
    border: 1px solid #c8e6c9;
    border-radius: 4px;
    background: #e8f5e9;
    color: #2e7d32;
    font-size: 11px;
    font-weight: 700;
    line-height: 1;
  }
  :global(.park-popup-ico svg) {
    display: block;
    width: 14px;
    height: 14px;
  }
  :global(.park-popup-ico-water) {
    border-color: #90caf9;
    background: #e3f2fd;
    color: #0277bd;
  }
  :global(.park-popup-ico-bench) {
    border-color: #d7ccc8;
    background: #efebe9;
    color: #6d4c41;
  }
  :global(.park-popup-ico-pond) {
    border-color: #81d4fa;
    background: #e1f5fe;
    color: #29b6f6;
  }
  :global(.park-popup-ico-pet) {
    border-color: #e0e0e0;
    background: #fff;
    color: #6d4c41;
  }
  :global(.park-popup-ico-clock) {
    border-color: #ffe082;
    background: #fff8e1;
    color: #f9a825;
  }
  :global(.park-popup-ico-toilet) {
    border-color: #263238;
    background: #455a64;
    color: #fff;
    font-size: 8px;
  }
  /* ボール遊びは可で試合形式だけ禁止のときに「試」バッジを並べる */
  :global(.park-popup-ico-ball) {
    width: auto;
    gap: 2px;
    padding: 0 2px;
  }
  :global(.park-popup-mini) {
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    min-width: 14px;
    height: 14px;
    padding: 0 2px;
    border: 1px solid #ffcdd2;
    border-radius: 3px;
    background: #ffebee;
    color: #c62828;
    font-size: 8px;
    font-weight: 700;
    line-height: 1;
  }
  /* 禁止の項目はアイコンの上に赤い×を重ねる */
  :global(.park-popup-ico.is-banned) {
    overflow: hidden;
  }
  :global(.park-popup-ico.is-banned)::after {
    content: "";
    position: absolute;
    inset: 0;
    border-radius: inherit;
    background:
      linear-gradient(45deg, transparent 47%, #d32f2f 47%, #d32f2f 53%, transparent 53%),
      linear-gradient(-45deg, transparent 47%, #d32f2f 47%, #d32f2f 53%, transparent 53%);
    pointer-events: none;
  }
  :global(.park-popup-meta) {
    margin-top: 0.1rem;
    color: #777;
    font-size: 0.7rem;
  }
  :global(.park-popup-links a::after) {
    content: none !important;
  }
  :global(.leaflet-popup-content) {
    max-height: 50vh;
    overflow: auto;
  }

  :global(.park-popup) {
    font-size: 0.82rem;
    line-height: 1.5;
    color: #1e293b;
  }
  :global(.park-popup strong) {
    font-size: 0.95rem;
  }
  :global(.park-popup-owner) {
    margin-left: 0.4rem;
    font-size: 0.7rem;
    color: #555;
  }
  :global(.park-popup-meta) {
    margin-top: 0.15rem;
    color: #444;
    font-size: 0.78rem;
  }
  :global(.park-popup-fac) {
    margin-top: 0.1rem;
    color: #2e7d32;
    font-size: 0.78rem;
  }
  :global(.park-popup-links) {
    display: flex;
    gap: 0.8rem;
    margin-top: 0.35rem;
  }
  :global(.park-popup-links a) {
    display: inline-flex;
    align-items: center;
    gap: 0.2rem;
    color: #0b57d0;
    font-weight: 700;
  }

  :global(.park-name-marker) {
    background: none;
    border: 0;
  }
  :global(.park-name-label) {
    position: absolute;
    left: 0;
    top: 0;
    transform: translate(-50%, 60%);
    background: rgba(255, 255, 255, 0.92);
    color: #1b5e20;
    font-size: 11px;
    font-weight: 700;
    line-height: 1.2;
    padding: 1px 4px;
    border-radius: 3px;
    white-space: nowrap;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
    pointer-events: none;
  }
  :global(.park-facility-tip) {
    background: rgba(255, 255, 255, 0.96);
    color: #4a148c;
    border: 1px solid #ce93d8;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 700;
    padding: 1px 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  }
  :global(.park-facility-tip.leaflet-tooltip-top::before) {
    display: none;
  }
  :global(.park-map.park-map-touch.leaflet-container) {
    touch-action: none;
  }
  :global(.park-map-fullscreen button) {
    width: 30px;
    height: 30px;
    border: 0;
    background: #fff;
    color: #1e293b;
    font-size: 18px;
    line-height: 1;
    cursor: pointer;
  }
  :global(.park-map-fullscreen button:hover) {
    background: #f1f5f9;
  }
  :global(.leaflet-overlay-pane path.park-selected) {
    filter: drop-shadow(0 0 6px rgba(27, 94, 32, 0.95));
    animation: park-selected-pulse 1.2s ease-in-out infinite;
  }
  :global(.leaflet-overlay-pane path.park-blink) {
    fill: #ffd54f;
    stroke: #ff6d00;
    animation: park-blink-pulse 2s ease-in-out infinite;
  }
  @keyframes park-selected-pulse {
    0%,
    100% {
      fill-opacity: 0.85;
      stroke-opacity: 1;
    }
    50% {
      fill-opacity: 0.2;
      stroke-opacity: 0.35;
    }
  }
  @keyframes park-blink-pulse {
    0%,
    100% {
      fill-opacity: 0.85;
      stroke-opacity: 1;
    }
    50% {
      fill-opacity: 0.35;
      stroke-opacity: 0.7;
    }
  }
  @media (prefers-reduced-motion: reduce) {
    :global(.leaflet-overlay-pane path.park-selected),
    :global(.leaflet-overlay-pane path.park-blink) {
      animation: none;
    }
  }
  /* 消火栓・防火水槽はチェックオンのときだけ表示する */
  :global(body:not(.show-fire) .park-fac-tank),
  :global(body:not(.show-fire) .park-fac-hydrant) {
    display: none;
  }

  .park-map-legend {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem 1rem;
    align-items: center;
    margin-top: 0.5rem;
    color: var(--sl-color-gray-2);
    font-size: 0.8rem;
  }
  .park-map-legend span {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
  }
  .swatch {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 2px;
  }
  .swatch-matched {
    background: #e53935;
  }
  .swatch-unmatched {
    background: #ffcdd2;
  }
  .swatch-nearby {
    background: #42a5f5;
  }
  .swatch-facility {
    background: #8e24aa;
    border-radius: 50%;
  }
  .swatch-facility-nearby {
    background: #fb8c00;
    border-radius: 50%;
  }
  .swatch-boundary {
    height: 0;
    border-top: 4px solid #6a1b9a;
    border-radius: 0;
    background: transparent;
  }
  .park-map-locate-status {
    margin-top: 0.3rem;
    color: var(--sl-color-gray-2);
    font-size: 0.8rem;
  }
  :global(.park-locate) {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    padding: 0;
    border: 0;
    border-radius: 50%;
    background: #fff;
    color: #1e88e5;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
    cursor: pointer;
  }
  :global(.park-locate:hover) {
    background: #f0f7ff;
  }
  :global(.park-locate.is-tracking) {
    background: #1e88e5;
    color: #fff;
    animation: park-locate-pulse 1.8s infinite;
  }
  :global(.park-locate.is-tracking:hover) {
    background: #1565c0;
  }
  @keyframes park-locate-pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(30, 136, 229, 0.45);
    }
    70% {
      box-shadow: 0 0 0 9px rgba(30, 136, 229, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(30, 136, 229, 0);
    }
  }
  :global(.park-locate svg) {
    display: block;
    width: 20px;
    height: 20px;
  }
  .park-map-note {
    margin-top: 0.4rem;
    color: var(--sl-color-gray-2);
    font-size: 0.8rem;
  }
  :global(.park-map-selected) {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    gap: 0.1rem 0.55rem;
    max-width: min(92vw, 340px);
    padding: 0.28rem 0.55rem;
    background: rgba(255, 255, 255, 0.95);
    border: 1px solid var(--sl-color-gray-5);
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.18);
    color: #1e293b;
    font-size: 0.8rem;
    line-height: 1.45;
  }
  :global(.park-map-selected[hidden]) {
    display: none;
  }
  :global(.park-map-selected-name) {
    font-weight: 700;
  }
  :global(.park-map-selected-owner) {
    padding: 0.02rem 0.3rem;
    border: 1px solid currentColor;
    border-radius: 999px;
    font-size: 0.68rem;
    font-weight: 600;
    opacity: 0.85;
  }
  :global(.park-map-selected-owner[hidden]) {
    display: none;
  }
  :global(.park-map-selected-note) {
    color: #666;
    font-size: 0.72rem;
  }
  :global(.park-map-selected a) {
    display: inline-flex;
    align-items: center;
    gap: 0.2rem;
    color: #0b57d0;
    white-space: nowrap;
  }
  :global(.park-map-selected:not([hidden])) {
    animation: park-map-selected-in 0.45s ease-out;
  }
  @keyframes park-map-selected-in {
    0% {
      opacity: 0;
      transform: translateY(14px) scale(0.95);
      box-shadow: 0 0 0 6px rgba(27, 94, 32, 0.45);
    }
    100% {
      opacity: 1;
      transform: none;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.18);
    }
  }
  @media (prefers-reduced-motion: reduce) {
    :global(.park-map-selected:not([hidden])) {
      animation: none;
    }
  }
  :global(.park-map-link-ico) {
    font-size: 1em;
    line-height: 1;
  }
  /* 公共施設の名前を遊具アイコンより下に置く */
  :global(.leaflet-tooltip-pane) {
    z-index: 590 !important;
  }
  .swatch-fac {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 18px;
    height: 18px;
    margin-right: 0.3rem;
    color: #fff;
    font-style: normal;
    font-size: 7px;
    font-weight: 700;
    line-height: 1;
  }
  .swatch-fac-toilet {
    background: #455a64;
    border-radius: 4px;
  }
  .swatch-fac-water {
    box-sizing: border-box;
    border: 1px solid #0277bd;
    border-radius: 50%;
    background: #fff;
    color: #0277bd;
  }
  :global(.park-fac-markers),
  :global(.park-fac-list) {
    pointer-events: none;
  }
  :global(.park-fac-list) {
    display: inline-flex;
    gap: 2px;
    transform: translate(-50%, -50%);
  }
  :global(.park-fac) {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 22px;
    height: 22px;
    color: #fff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
    font-size: 9px;
    font-weight: 700;
    line-height: 1;
  }
  :global(.park-fac-toilet) {
    background: #455a64;
    border: 1px solid #263238;
    border-radius: 5px;
  }
  :global(.park-fac-water) {
    border: 1px solid #0277bd;
    border-radius: 50%;
    background: #fff;
    color: #0277bd;
    font-size: 12px;
  }
  :global(.park-fac-clock) {
    background: #f9a825;
    border: 1px solid #f57f17;
    border-radius: 50%;
    color: #1b1b1b;
  }
  :global(.park-fac-tank) {
    background: #1565c0;
    border: 1px solid #0d47a1;
    border-radius: 5px;
  }
  :global(.park-fac-hydrant) {
    background: #c62828;
    border: 1px solid #8e0000;
    border-radius: 50%;
  }
  :global(.park-fac-unconfirmed) {
    background: #616161;
    border: 1px solid #212121;
    border-radius: 50%;
  }
  :global(.park-fac svg) {
    display: block;
  }
  :global(.park-facility-marker) {
    background: none;
    border: 0;
  }
  :global(.park-facility-emoji) {
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    width: 22px;
    height: 22px;
    border: 2px solid #8e24aa;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    font-size: 13px;
    line-height: 1;
  }
  :global(.park-facility-marker.is-nearby .park-facility-emoji) {
    border-color: #fb8c00;
  }
  :global(.park-play-markers),
  :global(.park-play-list) {
    pointer-events: none;
  }
  :global(.park-play-list) {
    display: inline-flex;
    gap: 2px;
    transform: translate(-50%, -50%) translateY(-24px);
  }
  :global(.park-play) {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border: 1px solid currentColor;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
    font-size: 9px;
    font-weight: 700;
    line-height: 1;
  }
  /* アイコンのクリックで公園を選択できるようにする(地図のドラッグは邪魔しない)。 */
  :global(.park-fac-markers .park-fac),
  :global(.park-play-markers .park-play) {
    pointer-events: auto;
    cursor: pointer;
  }
  :global(.park-play-plane) {
    color: #c62828;
  }
  :global(.park-play-swing) {
    color: #ef6c00;
  }
  :global(.park-play-toddler) {
    color: #8e24aa;
  }
  :global(.park-play-grass) {
    color: #2e7d32;
  }
  :global(.park-play-seesaw) {
    color: #6d4c41;
  }
  :global(.park-play-spring) {
    color: #d81b60;
  }
  :global(.park-play-slide) {
    color: #2e7d32;
  }
  :global(.park-play-jungle) {
    color: #6a1b9a;
  }
  :global(.park-play-sand) {
    color: #3e2723;
  }
  :global(.park-play-complex) {
    color: #0277bd;
  }
  :global(.park-play-ball) {
    color: #1b5e20;
  }
  :global(.park-play-special) {
    color: #f9a825;
  }
  :global(.park-play-pond) {
    color: #29b6f6;
  }
  :global(.park-play-rope) {
    color: #00838f;
  }
  :global(.park-locate-marker) {
    border: 0;
    background: none;
  }
  :global(.park-locate-arrow) {
    display: block;
    transform-origin: 50% 50%;
    filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.35));
  }
  .park-map-help {
    margin-top: 0.4rem;
  }
  .park-map-help summary {
    cursor: pointer;
    color: var(--sl-color-text-accent);
    font-size: 0.85rem;
  }
  .park-play-legend {
    display: flex;
    flex-wrap: wrap;
    gap: 0.35rem 0.8rem;
    margin: 0.5rem 0 0;
    color: var(--sl-color-gray-2);
    font-size: 0.78rem;
  }
  .park-play-legend-item {
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
  }
  :global(.park-play svg) {
    display: block;
    width: 100%;
    height: 100%;
  }
  :global(.park-play-swing svg) {
    width: 70%;
    height: 70%;
  }
  /* StarlightのMarkdown余白ルールがLeafletの各ペインに margin-top:1rem を
     付けて地図を下へずらすため、地図内のペインは余白なしにする。 */
  .park-map :global(.leaflet-pane) {
    margin: 0 !important;
  }
  /* Starlightの canvas/svg 向け max-width が Leaflet の描画領域を
     0幅にしてしまうため、地図内だけ上書きする。 */
  .park-map :global(.leaflet-overlay-pane canvas),
  .park-map :global(.leaflet-overlay-pane svg) {
    max-width: none !important;
    max-height: none !important;
    margin: 0 !important;
  }
  /* Starlightの画像用スタイル(margin / border / border-radius)が
     タイルに付くと、行ずれやタイルごとの枠が出るため打ち消す。 */
  .park-map :global(.leaflet-tile) {
    margin: 0 !important;
    border: 0 !important;
    border-radius: 0 !important;
  }
  @media (max-width: 640px) {
    .park-map {
      height: 360px;
    }
  }
</style>

<script>
  import L from "leaflet";
  import "leaflet/dist/leaflet.css";
  import geojson from "@/data/parks-geojson";
  import boundary from "@/data/kodaira-boundary.json";
  import nearbyData from "@/data/kodaira-nearby-parks.json";
  import facilities from "@/data/kodaira-facilities.json";
  import nearbyFacilities from "@/data/kodaira-nearby-facilities.json";
  import { PARK_ICONS } from "@/data/park-icons";
  import parks from "@/data/kodaira-parks.json";

  const MATCHED_STYLE = {
    color: "#2e7d32",
    weight: 1.5,
    fillColor: "#66bb6a",
    fillOpacity: 0.35,
  };
  const UNMATCHED_STYLE = {
    color: "#a5d6a7",
    weight: 1.2,
    fillColor: "#c8e6c9",
    fillOpacity: 0.25,
  };
  const DIM_STYLE = {
    color: "#c8e6c9",
    weight: 0.8,
    fillColor: "#e8f5e9",
    fillOpacity: 0.05,
    opacity: 0.2,
  };
  const SELECTED_STYLE = {
    color: "#1b5e20",
    weight: 3,
    fillColor: "#69f0ae",
    fillOpacity: 0.75,
  };
  const NEARBY_STYLE = {
    color: "#2e7d32",
    weight: 1.5,
    fillColor: "#66bb6a",
    fillOpacity: 0.35,
  };
  const NEARBY_POINT_STYLE = {
    radius: 7,
    color: "#1b5e20",
    weight: 2,
    fillColor: "#66bb6a",
    fillOpacity: 0.85,
  };
  const NEARBY_SELECTED_STYLE = {
    color: "#1b5e20",
    weight: 3,
    fillColor: "#69f0ae",
    fillOpacity: 0.75,
  };
  const NEARBY_DIM_STYLE = {
    color: "#c8e6c9",
    weight: 0.8,
    fillColor: "#e8f5e9",
    fillOpacity: 0.05,
    opacity: 0.2,
  };

  // 選択中の公園のグロー表示
  const markSelected = (lyr: any, selected: boolean) => {
    const element = lyr?.getElement?.();
    if (element && element.classList) {
      element.classList.toggle("park-selected", selected);
    }
  };
  // フィルタがないときの位置点滅
  const markBlink = (lyr: any, on: boolean) => {
    const element = lyr?.getElement?.();
    if (element && element.classList) {
      element.classList.toggle("park-blink", on);
    }
  };

  const el = document.getElementById("park-map");
  if (el && !el.dataset.initialized) {
    el.dataset.initialized = "1";

    const isTouch =
      L.Browser.mobile || window.matchMedia("(pointer: coarse)").matches;
    const map = L.map(el, {
      // タッチ端末では1本指のドラッグを無効にし、ページのスクロールを妨げない。
      // 地図の移動・拡大は2本指(touchZoom)で行う。
      dragging: !isTouch,
      touchZoom: true,
      scrollWheelZoom: true,
      zoomSnap: 1,
      zoomDelta: 1,
      zoomAnimation: false,
      fadeAnimation: false,
      markerZoomAnimation: false,
    }).setView([35.728, 139.477], 13);

    // タッチ端末では touch-action: none にして2本指ジェスチャーをLeafletに届け、
    // 1本指の縦ドラッグはページスクロールとして自前で処理する。
    if (isTouch) {
      el.classList.add("park-map-touch");
      let tracking = false;
      let lastX = 0;
      let lastY = 0;
      el.addEventListener(
        "touchstart",
        (e: TouchEvent) => {
          if (
            document.fullscreenElement === el ||
            el.classList.contains("is-maximized")
          ) {
            tracking = false;
            return;
          }
          if (e.touches.length !== 1) {
            tracking = false;
            return;
          }
          const target = e.target as Element | null;
          if (target && target.closest(".leaflet-control")) {
            tracking = false;
            return;
          }
          tracking = true;
          lastX = e.touches[0].clientX;
          lastY = e.touches[0].clientY;
        },
        { passive: true },
      );
      el.addEventListener(
        "touchmove",
        (e: TouchEvent) => {
          if (
            document.fullscreenElement === el ||
            el.classList.contains("is-maximized")
          ) {
            return;
          }
          if (!tracking || e.touches.length !== 1) return;
          const x = e.touches[0].clientX;
          const y = e.touches[0].clientY;
          const dx = x - lastX;
          const dy = y - lastY;
          if (Math.abs(dy) >= Math.abs(dx)) {
            e.preventDefault();
            window.scrollBy(0, -dy);
            lastX = x;
            lastY = y;
          }
        },
        { passive: false },
      );
      const stopTracking = () => {
        tracking = false;
      };
      el.addEventListener("touchend", stopTracking);
      el.addEventListener("touchcancel", stopTracking);
    }

    // 帰属表示の「Leaflet」旗アイコンを消す(OSMの表示は残す)。
    map.attributionControl.setPrefix(false);

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

    // 全画面のときだけ、地図内にフィルターのパネルを出す
    const filterPanel = document.createElement("div");
    filterPanel.className = "park-map-filter-panel";
    filterPanel.hidden = true;
    const filterToggle = document.createElement("button");
    filterToggle.type = "button";
    filterToggle.className = "park-map-filter-toggle";
    filterToggle.innerHTML =
      '絞り込み <span class="park-map-filter-status" hidden>適用中</span> <span class="park-map-filter-caret" aria-hidden="true">▾</span>';
    const filterStatus = filterToggle.querySelector<HTMLElement>(".park-map-filter-status");
    const filterCaret = filterToggle.querySelector<HTMLElement>(".park-map-filter-caret");
    const filterBody = document.createElement("div");
    filterBody.className = "park-map-filter-body";
    filterBody.hidden = true;
    const filterFooter = document.createElement("div");
    filterFooter.className = "park-map-filter-footer";
    filterFooter.innerHTML = "<span>情報には誤りが含まれる場合があります。</span>";
    const filterClose = document.createElement("button");
    filterClose.type = "button";
    filterClose.className = "park-map-filter-close";
    filterClose.textContent = "閉じる";
    filterClose.addEventListener("click", () => {
      filterBody.hidden = true;
      if (filterCaret) filterCaret.textContent = "▾";
    });
    filterFooter.appendChild(filterClose);
    filterPanel.append(filterToggle, filterBody, filterFooter);
    L.DomEvent.disableClickPropagation(filterPanel);
    L.DomEvent.disableScrollPropagation(filterPanel);
    filterToggle.addEventListener("click", () => {
      filterBody.hidden = !filterBody.hidden;
      if (filterCaret) filterCaret.textContent = filterBody.hidden ? "▾" : "▴";
    });

    let filterHome: { parent: Node; next: Node | null } | null = null;

    const setFiltersInMap = (on: boolean) => {
      const controls = document.querySelector<HTMLElement>(".parks-controls");
      if (on) {
        if (!controls || filterHome) return;
        filterHome = {
          parent: controls.parentNode as Node,
          next: controls.nextSibling,
        };
        filterBody.append(controls);
        map.getContainer().appendChild(filterPanel);
        filterPanel.hidden = false;
        filterBody.hidden = false;
        if (filterCaret) filterCaret.textContent = "▴";
      } else if (filterHome && controls) {
        filterHome.parent.insertBefore(controls, filterHome.next);
        filterPanel.remove();
        filterPanel.hidden = true;
        filterHome = null;
      }
    };

    const FullscreenControl = L.Control.extend({
      onAdd: () => {
        const container = L.DomUtil.create("div", "leaflet-bar park-map-fullscreen");
        const button = L.DomUtil.create("button", "", container);
        button.type = "button";
        button.title = "全画面表示";
        button.setAttribute("aria-label", "全画面表示");
        button.innerHTML = "⛶";
        L.DomEvent.disableClickPropagation(container);
        L.DomEvent.disableScrollPropagation(container);

        const target = map.getContainer();
        const isCssMax = () => target.classList.contains("is-maximized");
        const update = () => {
          const active = document.fullscreenElement === target || isCssMax();
          button.innerHTML = active ? "✕" : "⛶";
          button.title = active ? "全画面を終了" : "全画面表示";
          button.setAttribute("aria-label", button.title);
          setFiltersInMap(active);
          // 全画面中は1本指でも地図を動かせるようにする(PCのドラッグと同じ)。
          if (isTouch) {
            if (active) map.dragging.enable();
            else map.dragging.disable();
          }
          window.setTimeout(() => map.invalidateSize(), 60);
          window.setTimeout(() => map.invalidateSize(), 350);
        };
        let maxHome: { parent: Node; next: Node | null } | null = null;
        const enterCssMax = () => {
          if (!maxHome) {
            maxHome = { parent: target.parentNode as Node, next: target.nextSibling };
            document.body.appendChild(target);
          }
          target.classList.add("is-maximized");
          document.body.classList.add("park-map-maximized");
          update();
        };
        const exitCssMax = () => {
          target.classList.remove("is-maximized");
          document.body.classList.remove("park-map-maximized");
          if (maxHome) {
            maxHome.parent.insertBefore(target, maxHome.next);
            maxHome = null;
          }
          update();
        };

        L.DomEvent.on(button, "click", (ev: Event) => {
          L.DomEvent.stop(ev);
          if (document.fullscreenElement === target) {
            document.exitFullscreen?.().catch(() => exitCssMax());
            return;
          }
          if (isCssMax()) {
            exitCssMax();
            return;
          }
          // Fullscreen API が使えない端末(iPhoneなど)はCSSで最大化する。
          if (document.fullscreenEnabled && target.requestFullscreen) {
            target.requestFullscreen().catch(() => enterCssMax());
          } else {
            enterCssMax();
          }
        });

        document.addEventListener("fullscreenchange", update);
        document.addEventListener("keydown", (ev) => {
          if (ev.key === "Escape" && isCssMax()) exitCssMax();
        });
        return container;
      },
    });
    new FullscreenControl({ position: "topright" }).addTo(map);

    const layersByName = new Map<string, any>();

    // 消火栓・防火水槽はチェックオンのときだけ表示する
    const fireToggle = document.querySelector<HTMLInputElement>("[data-show-fire]");
    if (fireToggle) {
      const applyFire = () =>
        document.body.classList.toggle("show-fire", fireToggle.checked);
      fireToggle.addEventListener("change", applyFire);
      applyFire();
    }
    const allLayers: any[] = [];
    type NearbyEntry = { name: string; layer: any; city: string; key: string };
    const nearbyEntries: NearbyEntry[] = [];
    const nearbyInfoByName = new Map<string, any>();
    ((nearbyData as any).features ?? []).forEach((f: any) => {
      const p = f.properties || {};
      const name = String(p.name || "").trim();
      if (name) nearbyInfoByName.set(name, p);
    });
    const nearbyMapsQuery = (name: string, city = "") =>
      name ? (city && !name.startsWith(city) ? `${city}${name}` : name) : "";
    const nearbyBaseStyle = (lyr: any) =>
      lyr._isPoint ? NEARBY_POINT_STYLE : NEARBY_STYLE;
    const parkDataByName = new Map<string, any>();
    (parks as any[]).forEach((p) => parkDataByName.set(p["公園名"], p));
    const ownerByName = new Map<string, string>();
    parkDataByName.forEach((p, name) => {
      const owner = (p["設置者"] || "").trim();
      if (owner && owner !== "小平市") ownerByName.set(name, owner);
    });
    const ownerLabel = (owner: string) =>
      owner.includes("都営")
        ? "都営"
        : owner === "東京都"
          ? "都立"
          : owner.includes("UR")
            ? "UR"
            : owner.includes("民間")
              ? "民間"
              : owner;

    const escapePopup = (value: string) =>
      value.replace(/[&<>"']/g, (ch) =>
        ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch] as string,
      );
    const buildPopup = (ourName: string, osmName: string, owner = "", mapsQuery = "") => {
      // 市外の近隣公園は kodaira-parks.json にないので、近隣データの属性を使う。
      const rec = parkDataByName.get(ourName) || nearbyInfoByName.get(ourName);
      const name = escapePopup(ourName || osmName || "");
      const addr = escapePopup(rec?.["住所"] || "");
      // 近隣データは面積㎡が空で area_m2 に入っていることがある。
      const areaRaw = Number(
        String(rec?.["面積㎡"] || "").trim() || rec?.["area_m2"] || 0,
      );
      const area =
        Number.isFinite(areaRaw) && areaRaw > 0
          ? `${areaRaw.toLocaleString("ja-JP")}㎡`
          : "";
      const type = escapePopup(rec?.["種別"] || "");
      // 詳細行の項目名はアイコンで示し、文字量を抑える。
      const DISASTER_KEEP = /かまど|カマド|防災収納|レスキュー|防災器具|避難/;
      const disaster = String(rec?.["防災用具"] || "")
        .split(/[、,]/)
        .map((s) => s.trim())
        .filter((s) => s && !s.includes("防火水槽") && !s.includes("消火栓"))
        .filter((s) => DISASTER_KEEP.test(s))
        .join("、");
      const waterRaw = String(rec?.["水飲み場"] || "").trim();
      // 水飲み場は数量ではなく有無だけを、分かるように表示する。
      const water = waterRaw
        ? /[??]/.test(waterRaw)
          ? "水飲み場あり?"
          : "水飲み場あり"
        : "水飲み場なし";
      // ○/〇 などの表記は「〜あり」にして意味が分かるようにする。
      const presence = (label: string, value: unknown) => {
        const v = String(value ?? "").trim();
        if (!v) return "";
        return /^[○〇◯あり有1]+$/.test(v) ? `${label}あり` : v;
      };
      // ボール遊びは、試合形式の可否を括弧書きで添える。
      const ballText = String(rec?.["ボール遊び"] || "").trim();
      const matchText = String(rec?.["試合形式のボール遊び"] || "").trim();
      const ball =
        ballText && matchText ? `${ballText}(試合形式${matchText})` : ballText;
      // 項目名は1文字の文字アイコンで示す(水・ベンチ・池は絵アイコン)。
      const rowIcons: Record<string, string> = {
        遊具: "遊",
        トイレ: "WC",
        水飲み場: PARK_ICONS.water.svg,
        "ベンチ・椅子": PARK_ICONS.bench.svg,
        野外卓: PARK_ICONS.picnic.svg,
        "シェルター等": PARK_ICONS.shelter.svg,
        草地広場: PARK_ICONS.grass.svg,
        多目的広場: "広",
        築山: PARK_ICONS.mountain.svg,
        じゃぶじゃぶ池: PARK_ICONS.pond.svg,
        ボール遊び: PARK_ICONS.ball.svg,
        ペット: PARK_ICONS.dog.svg,
        時計: PARK_ICONS.clock.svg,
        防災用具: "災",
      };
      const rows = [
        ["遊具", rec?.["遊具"]],
        ["トイレ", rec?.["トイレ"]],
        ["水飲み場", water],
        ["ベンチ・椅子", rec?.["ベンチ・椅子"]],
        ["野外卓", rec?.["野外卓"]],
        ["シェルター等", rec?.["シェルター等"]],
        ["草地広場", presence("草地広場", rec?.["草地広場"])],
        ["多目的広場", presence("多目的広場", rec?.["多目的広場"])],
        ["築山", presence("築山", rec?.["築山"])],
        ["じゃぶじゃぶ池", presence("じゃぶじゃぶ池", rec?.["じゃぶじゃぶ池"])],
        ["ボール遊び", ball],
        ["ペット", rec?.["ペット"]],
        ["時計", presence("時計", rec?.["時計"])],
        ["防災用具", disaster],
      ].filter(([, value]) => value && String(value).trim());
      const ROW_MOD: Record<string, string> = {
        "水飲み場": " park-popup-ico-water",
        "ベンチ・椅子": " park-popup-ico-bench",
        "じゃぶじゃぶ池": " park-popup-ico-pond",
        "ペット": " park-popup-ico-pet",
        "時計": " park-popup-ico-clock",
        "トイレ": " park-popup-ico-toilet",
      };
      const detailHtml = rows
        .map(([label, value]) => {
          const labelText = String(label);
          const valueText = String(value);
          const isBall = labelText === "ボール遊び";
          // ボール遊び全体が禁止ならボールに×、試合形式だけ禁止なら「試」に×を付ける。
          const banned = isBall ? /禁止/.test(ballText) : /禁止/.test(valueText);
          let iconHtml = rowIcons[labelText] || "";
          if (isBall && !banned && /禁止/.test(matchText)) {
            iconHtml += '<span class="park-popup-mini" title="試合形式は禁止">試×</span>';
          }
          const icoClass = `park-popup-ico${ROW_MOD[labelText] || ""}${banned ? " is-banned" : ""}${isBall ? " park-popup-ico-ball" : ""}`;
          return `<div class="park-popup-row" title="${escapePopup(labelText)}"><span class="${icoClass}" role="img" aria-label="${escapePopup(labelText)}">${iconHtml}</span><span class="park-popup-val">${escapePopup(valueText)}</span></div>`;
        })
        .join("");
      const query = mapsQuery || (ourName ? `小平市${ourName}` : "");
      const dest =
        rec?.["緯度"] && rec?.["経度"]
          ? `${rec["緯度"]},${rec["経度"]}`
          : query;
      const maps =
        rec?.["地図URL"] ||
        `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
      const route = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(dest)}&travelmode=walking`;
      return `<div class="park-popup"><strong>${name}</strong>${owner ? `<span class="park-popup-owner">${escapePopup(owner)}</span>` : ""}${addr || area || type ? `<div class="park-popup-meta">${[addr, area, type].filter(Boolean).join(" ・ ")}</div>` : ""}${detailHtml}<div class="park-popup-links"><a href="${maps}" target="_blank" rel="noopener">🌏Google</a><a href="${route}" target="_blank" rel="noopener">🚶経路</a></div></div>`;
    };

    const filterName = (name: string, scroll = false) => {
      document.dispatchEvent(
        new CustomEvent("park:filter-name", { detail: { name, scroll } }),
      );
    };

    // 選択中の公園を地図左下に控えめに表示する(ポップアップは使わない)。
    let selectedBar: HTMLElement | null = null;
    let selectedNameEl: HTMLElement | null = null;
    let selectedMapsLink: HTMLAnchorElement | null = null;
    let selectedRouteLink: HTMLAnchorElement | null = null;
    let selectedNoteEl: HTMLElement | null = null;
    let selectedOwnerEl: HTMLElement | null = null;

    const showSelected = (
      ourName: string,
      osmName: string,
      listed = true,
      owner = "",
      mapsQuery = "",
    ) => {
      if (!selectedBar || !selectedNameEl || !selectedMapsLink) return;
      selectedNameEl.textContent = ourName;
      selectedNameEl.title =
        osmName && osmName !== ourName ? `OSM: ${osmName}` : "";
      // 経路検索(現在地からのルート)を開く。
      const rec = parkDataByName.get(ourName);
      const name = (ourName || "").trim();
      const query = mapsQuery || (name
        ? `小平市${name}`
        : rec?.["住所"]
          ? `小平市${rec["住所"]}`
          : rec?.["緯度"] && rec?.["経度"]
            ? `${rec["緯度"]},${rec["経度"]}`
            : "小平市");
      const destination =
        rec?.["緯度"] && rec?.["経度"]
          ? `${rec["緯度"]},${rec["経度"]}`
          : query;
      selectedMapsLink.href =
        rec?.["地図URL"] ||
        `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
      if (selectedRouteLink) {
        selectedRouteLink.href = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(destination)}&travelmode=walking`;
      }
      if (selectedNoteEl) selectedNoteEl.hidden = listed;
      if (selectedOwnerEl) {
        selectedOwnerEl.textContent = owner ? ownerLabel(owner) : "";
        selectedOwnerEl.hidden = !owner;
      }
      selectedBar.hidden = false;
    };

    const SelectedControl = L.Control.extend({
      onAdd: () => {
        const box = L.DomUtil.create("div", "park-map-selected");
        box.hidden = true;
        box.innerHTML =
          '<span class="park-map-selected-name"></span>' +
          '<span class="park-map-selected-owner" hidden></span>' +
          '<span class="park-map-selected-note" hidden>一覧にない緑地・公園</span>' +
          '<a data-park-maps-link href="#" target="_blank" rel="noopener"><span class="park-map-link-ico" aria-hidden="true">🗺</span>Gマップ</a>' +
          '<a data-park-route-link href="#" target="_blank" rel="noopener"><span class="park-map-link-ico" aria-hidden="true">🚶</span>経路</a>';
        selectedBar = box;
        selectedNameEl = box.querySelector<HTMLElement>(".park-map-selected-name");
        selectedMapsLink = box.querySelector<HTMLAnchorElement>("[data-park-maps-link]");
        selectedRouteLink = box.querySelector<HTMLAnchorElement>("[data-park-route-link]");
        selectedNoteEl = box.querySelector<HTMLElement>(".park-map-selected-note");
        selectedOwnerEl = box.querySelector<HTMLElement>(".park-map-selected-owner");
        L.DomEvent.disableClickPropagation(box);
        return box;
      },
    });
    new SelectedControl({ position: "bottomleft" }).addTo(map);

    const layer = L.geoJSON(geojson as any, {
      bubblingMouseEvents: false,
      style: (feature: any) =>
        feature?.properties?.matched ? MATCHED_STYLE : UNMATCHED_STYLE,
      onEachFeature: (feature: any, lyr: any) => {
        const p = feature.properties || {};
        const name = p.name || "名称未設定";
        const ourName = p.our_name || "";
        lyr._parkName = ourName;
        lyr._osmName = name;
        allLayers.push(lyr);
        if (ourName) {
          const existing = layersByName.get(ourName);
          if (!existing) {
            layersByName.set(ourName, lyr);
          } else if (
            typeof existing.getLayers === "function" &&
            typeof existing.addLayer === "function"
          ) {
            existing.addLayer(lyr);
          } else {
            const group = L.featureGroup([existing, lyr]);
            group._osmName = existing._osmName;
            layersByName.set(ourName, group);
          }
        }

        if (ourName) {
          lyr.on("add", () => {
            const path = lyr.getElement?.();
            if (path) path.setAttribute("data-park", ourName);
          });
          lyr.bindPopup(buildPopup(ourName, name, ownerByName.get(ourName) || ""), {
            maxWidth: 300,
          });
          lyr.on("popupopen", () => {
            lyr.setStyle(SELECTED_STYLE);
            markSelected(lyr, true);
            markBlink(lyr, false);
            lyr.bringToFront?.();
          });
          lyr.on("popupclose", () => {
            lyr.setStyle(MATCHED_STYLE);
            markSelected(lyr, false);
            markBlink(lyr, true);
          });
          lyr.on("click", (ev: any) => {
            if (ev?.originalEvent) L.DomEvent.stopPropagation(ev.originalEvent);
            document.dispatchEvent(
              new CustomEvent("park:select-row", { detail: { name: ourName } }),
            );
          });
        } else {
          // 一覧にない公園・緑地は表示だけ。クリックには反応させない。
          lyr.on("add", () => {
            const path = lyr.getElement?.();
            if (path) path.classList.remove("leaflet-interactive");
          });
        }
      },
    }).addTo(map);

    // 市外を薄く覆い、小平市内の部分だけを見せるマスク。
    // 境界線より先に追加して、境界線がマスクの上に描かれるようにする。
    const boundaryGeom = (boundary as any).features[0].geometry;
    const boundaryRings =
      boundaryGeom.type === "Polygon"
        ? boundaryGeom.coordinates
        : boundaryGeom.coordinates.map((p: any) => p[0]);
    const WORLD_RING = [
      [-180, -85],
      [180, -85],
      [180, 85],
      [-180, 85],
      [-180, -85],
    ];
    L.geoJSON(
      {
        type: "Feature",
        properties: {},
        geometry: {
          type: "Polygon",
          coordinates: [WORLD_RING, ...boundaryRings],
        },
      } as any,
      {
        style: { fillColor: "#ffffff", fillOpacity: 0.78, stroke: false },
        interactive: false,
      },
    ).addTo(map);

    // 小平市の境界線(塗りなし・太い実線)
    const boundaryLayer = L.geoJSON(boundary as any, {
      style: {
        color: "#6a1b9a",
        weight: 4,
        opacity: 0.9,
        fill: false,
      },
      interactive: false,
    }).addTo(map);

    // 市外の近い公園(500m以内)は別レイヤーにする。
    // 小平市内の公園と同じく、クリックで一覧を絞り込み、左下に情報を表示する。
    const nearbyLayer = L.geoJSON(nearbyData as any, {
      // 範囲が取得できない公園は点(丸)で表示する。
      pointToLayer: (_feature: any, latlng: any) =>
        L.circleMarker(latlng, NEARBY_POINT_STYLE),
      style: (feature: any) =>
        feature?.geometry?.type === "Point" ? NEARBY_POINT_STYLE : NEARBY_STYLE,
      onEachFeature: (feature: any, lyr: any) => {
        const p = feature.properties || {};
        const name = String(p.name || "").trim();
        const city = String(p.city || "").trim();
        const key = `${p.osm_type || ""}/${p.osm_id || ""}`;
        lyr._isPoint = feature.geometry?.type === "Point";
        if (name) nearbyEntries.push({ name, layer: lyr, city, key });
        if (name) {
          lyr.bindPopup(buildPopup(name, name, city ? `市外・${city}` : "", nearbyMapsQuery(name, city)), {
            maxWidth: 300,
          });
          lyr.on("popupopen", () => {
            lyr.setStyle(NEARBY_SELECTED_STYLE);
            markSelected(lyr, true);
            markBlink(lyr, false);
            lyr.bringToFront?.();
          });
          lyr.on("popupclose", () => {
            lyr.setStyle(nearbyBaseStyle(lyr));
            markSelected(lyr, false);
            markBlink(lyr, true);
          });
        }
        lyr.on("click", (ev: any) => {
          if (ev?.originalEvent) L.DomEvent.stopPropagation(ev.originalEvent);
          if (!name) return;
          document.dispatchEvent(
            new CustomEvent("park:select-row", { detail: { name } }),
          );
        });
      },
    }).addTo(map);

    // 遊具・設備アイコンをクリックしたときも、その公園を選択する。
    const openParkPopup = (name: string) => {
      let layer: any = layersByName.get(name);
      if (layer && typeof layer.getLayers === "function") {
        layer = layer.getLayers()[0] || layer;
      }
      if (!layer) {
        const entry = nearbyEntries.find((e) => e.name === name);
        layer = entry?.layer || null;
      }
      if (!layer) return;
      if (typeof layer.openPopup === "function") {
        const latlng = layer.getBounds
          ? layer.getBounds().getCenter()
          : layer.getLatLng?.();
        layer.openPopup(latlng);
      }
      document.dispatchEvent(
        new CustomEvent("park:select-row", { detail: { name } }),
      );
    };
    // アイコンのマーカーに公園名を持たせ、クリックでその公園を選択できるようにする。
    // 地図側のクリック処理がフキダシを閉じてしまうので、伝播は止める。
    const markIconOwner = (marker: any, name: string) => {
      const bind = () => {
        const el = marker.getElement?.();
        if (!el || el.getAttribute("data-park") === name) return;
        el.setAttribute("data-park", name);
        L.DomEvent.on(el, "click", (e: any) => {
          L.DomEvent.stopPropagation(e);
          openParkPopup(name);
        });
      };
      if (marker.getElement?.()) bind();
      else marker.on("add", bind);
    };

    // 地域センター・公民館・図書館・市役所支所・文化施設。
    // 市外の近隣施設はオレンジで表示する。
    const publicFacilityLayer = L.layerGroup();
    const facilityMarkers: { name: string; layer: any }[] = [];
    const FACILITY_ICON: Record<string, string> = {
      地域センター: "📍",
      公民館: "🏛",
      児童館: "🧒",
      図書館: "📚",
      市役所支所: "🏢",
      文化施設: "🎭",
    };
    const setFacilityOpacity = (layer: any, show: boolean) => {
      if (typeof layer.setOpacity === "function") {
        layer.setOpacity(show ? 1 : 0.2);
      } else if (typeof layer.setStyle === "function") {
        layer.setStyle({
          opacity: show ? 1 : 0.15,
          fillOpacity: show ? 0.85 : 0.1,
        });
      }
    };
    const addFacilities = (list: any[], nearby: boolean) => {
      list.forEach((f) => {
        if (f.lat == null || f.lon == null) return;
        const icon = FACILITY_ICON[f.type] || "";
        const marker = L.marker([f.lat, f.lon], {
          icon: L.divIcon({
            className: `park-facility-marker${nearby ? " is-nearby" : ""}`,
            html: `<span class="park-facility-emoji">${icon || "🏢"}</span>`,
            iconSize: [22, 22],
            iconAnchor: [11, 11],
          }),
        })
          .bindPopup(
            `<strong>${icon} ${f.name}</strong>${nearby ? "(市外)" : ""}<br>${f.type}<br>${f.hours || ""}${f.closed ? `<br>休: ${f.closed}` : ""}<br>トイレ: ${f.toilet || "未確認"} / 給水: ${f.water || "未確認"}`,
          )
          .addTo(publicFacilityLayer);
        const rawName = String(f.name || "");
        const shortName =
          rawName.length > 12 ? `${rawName.slice(0, 11)}…` : rawName;
        marker.bindTooltip(shortName, {
          direction: "top",
          offset: [0, -12],
          className: "park-facility-tip",
        });
        facilityMarkers.push({ name: String(f.name || ""), layer: marker });
      });
    };
    addFacilities(facilities as any[], false);
    addFacilities(nearbyFacilities as any[], true);
    publicFacilityLayer.addTo(map);

    // 道路で分かれた公園など、同じ公園に複数のポリゴンがある場合は
    // いちばん大きいポリゴンの中心にアイコンを置く。
    const centerOfLayer = (lyr: any) => {
      if (lyr && typeof lyr.getLayers === "function") {
        let best: any = null;
        let bestArea = -1;
        for (const child of lyr.getLayers()) {
          const b = child.getBounds();
          const area = (b.getNorth() - b.getSouth()) * (b.getEast() - b.getWest());
          if (area > bestArea) {
            bestArea = area;
            best = child;
          }
        }
        if (best) return best.getBounds().getCenter();
      }
      return lyr.getBounds().getCenter();
    };

    // 拡大時だけ表示する設備アイコン(トイレ・水飲み場)
    // 一覧と一致した公園のポリゴン内にだけ表示する。
    const facilityLayer = L.layerGroup();
    const facilityMarkersByName = new Map<string, any[]>();
    const playMarkersByName = new Map<string, any[]>();
    layersByName.forEach((lyr, name) => {
      const p = parkDataByName.get(name);
      if (!p) return;
      const icons: string[] = [];
      if ((p["トイレ"] || "").trim()) {
        icons.push(
          '<span class="park-fac park-fac-toilet" title="トイレあり" aria-label="トイレあり">WC</span>',
        );
      }
      if ((p["水飲み場"] || "").trim()) {
        icons.push(
          '<span class="park-fac park-fac-water" title="水飲み場あり" aria-label="水飲み場あり"><svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3.5c3.5 4.2 6 7.4 6 10.3a6 6 0 0 1-12 0c0-2.9 2.5-6.1 6-10.3z"/></svg></span>',
        );
      }
      const clock = (p["時計"] || "").trim();
      if (clock === "○" || clock === "あり" || clock === "有" || clock === "1") {
        icons.push(
          '<span class="park-fac park-fac-clock" title="時計あり" aria-label="時計あり"><svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 7v5l3 2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span>',
        );
      }
      const disaster = p["防災用具"] || "";
      if (/防火水槽[x×]\d+/.test(disaster)) {
        icons.push(
          '<span class="park-fac park-fac-tank" title="防火水槽あり" aria-label="防火水槽あり">槽</span>',
        );
      }
      if (/消火栓[x×]\d+/.test(disaster)) {
        icons.push(
          '<span class="park-fac park-fac-hydrant" title="消火栓あり" aria-label="消火栓あり">消</span>',
        );
      }
      if ((p["備考"] || "").includes("未確認")) {
        icons.push(
          '<span class="park-fac park-fac-unconfirmed" title="情報未確認" aria-label="情報未確認">?</span>',
        );
      }
      if (!icons.length) return;
      const center = centerOfLayer(lyr);
      const marker = L.marker([center.lat, center.lng], {
        icon: L.divIcon({
          className: "park-fac-markers",
          html: `<span class="park-fac-list">${icons.join("")}</span>`,
          iconSize: null,
          iconAnchor: [0, 0],
        }),
        riseOnHover: false,
        interactive: false,
      }).addTo(facilityLayer);
      markIconOwner(marker, name);
      const list = facilityMarkersByName.get(name) || [];
      list.push(marker);
      facilityMarkersByName.set(name, list);
    });

    // 拡大時だけ表示する遊具アイコン。
    // 公園ポリゴンの中心に、遊具の種類を絵アイコンで表示する。
    // スイング遊具・健康遊具の判定用(一覧表の facTokens と同じ名前で判定する)
    const PLAY_SPRING_TOKENS = [
      "スプリング",
      "スイング",
      "リトルポップ",
      "リンクミニ",
      "ルッキンロッキン",
      "リーフィー",
      "チューリー",
      "ロッキンパッピー",
      "ロッキンパピー",
      "ビー",
      "ハッピー",
      "ハニー",
      "クップル",
      "ウゴウゴ",
    ];
    const PLAY_HEALTH_TOKENS = [
      "フィットコンビ",
      "レグオーバー",
      "アームウォーカー",
      "ホップオーバー",
      "ジャンプ・ステップ",
      "立位体前屈",
      "懸垂",
      "垂直飛び",
      "閉眼片足立ち",
      "腕歩行",
      "リラックスボード",
      "パネルラダー",
      "棒とびこし",
      "脚のばし",
      "ふみいたストレッチ",
    ];
    const PLAY_STANDARD_TOKENS = [
      "ブランコ",
      "ぶらんこ",
      "滑台",
      "滑り台",
      "すべり台",
      "砂場",
      "鉄棒",
      "複合遊具",
      "ジャングル",
      "ヒコーキ",
      "飛行機",
      "シーソー",
      // 次の遊具は「特殊遊具」扱いにしない(別の分類・設備のため)
      "ロープスイング",
      "ロープウェイ",
      "バスケ",
      ...PLAY_SPRING_TOKENS,
      ...PLAY_HEALTH_TOKENS,
    ];
    const PLAY_DEFS = [
      { tokens: ["ヒコーキ", "飛行機"], key: "airplane", title: PARK_ICONS.airplane.title, cls: "park-play-plane", icon: PARK_ICONS.airplane.svg },
      { tokens: ["ジャングル"], key: "climbing", title: PARK_ICONS.climbing.title, cls: "park-play-jungle", icon: PARK_ICONS.climbing.svg },
      { tokens: [], key: "toddlerSwing", title: PARK_ICONS.toddlerSwing.title, cls: "park-play-toddler", icon: PARK_ICONS.toddlerSwing.svg },
      { tokens: ["ブランコ"], key: "swing", title: PARK_ICONS.swing.title, cls: "park-play-swing", icon: PARK_ICONS.swing.svg },
      { tokens: ["シーソー"], key: "seesaw", title: PARK_ICONS.teeter.title, cls: "park-play-seesaw", icon: PARK_ICONS.teeter.svg },
      { tokens: PLAY_SPRING_TOKENS, key: "spring", title: PARK_ICONS.spring.title, cls: "park-play-spring", icon: PARK_ICONS.spring.svg },
      { tokens: ["滑り台", "滑台"], key: "slide", title: PARK_ICONS.slide.title, cls: "park-play-slide", icon: PARK_ICONS.slide.svg },
      { tokens: ["ロープウェイ"], key: "flyingfox", title: PARK_ICONS.flyingfox.title, cls: "park-play-rope", icon: PARK_ICONS.flyingfox.svg },
      { tokens: ["砂場"], key: "sand", title: PARK_ICONS.sand.title, cls: "park-play-sand", icon: PARK_ICONS.sand.svg },
      { tokens: ["複合遊具"], key: "playground", title: PARK_ICONS.playground.title, cls: "park-play-complex", icon: PARK_ICONS.playground.svg },
      { tokens: [], key: "ball", title: PARK_ICONS.ball.title, cls: "park-play-ball", icon: PARK_ICONS.ball.svg },
      { tokens: [], key: "pond", title: PARK_ICONS.pond.title, cls: "park-play-pond", icon: PARK_ICONS.pond.svg },
      { tokens: [], key: "grass", title: PARK_ICONS.grass.title, cls: "park-play-grass", icon: PARK_ICONS.grass.svg },
      { tokens: [], key: "special", title: PARK_ICONS.special.title, cls: "park-play-special", icon: PARK_ICONS.special.svg },
    ];
    const playLegend = document.querySelector<HTMLElement>("[data-play-legend]");
    if (playLegend) {
      playLegend.innerHTML = PLAY_DEFS.map(
        (def) =>
          `<span class="park-play-legend-item"><span class="park-play ${def.cls}" aria-hidden="true">${def.icon}</span>${def.title}</span>`,
      ).join("");
    }
    const playLayer = L.layerGroup();
    layersByName.forEach((lyr, name) => {
      const p = parkDataByName.get(name);
      if (!p) return;
      const text = (p["遊具"] || "").trim();
      const ballText = (p["ボール遊び"] || "").trim();
      const hasBall = Boolean(ballText && ballText !== "禁止");
      const hasPond = Boolean((p["じゃぶじゃぶ池"] || "").trim());
      const hasGrass = Boolean(String(p["草地広場"] || "").trim());
      if (!text && !hasBall && !hasPond && !hasGrass) return;
      const segments = text
        .split(/[、,]/)
        .map((s) => s.trim())
        .filter(Boolean);
      // ロープスイングはスイング遊具ではないので spring には含めない。
      const isSpring = segments.some(
        (seg) =>
          !seg.includes("ロープスイング") &&
          PLAY_SPRING_TOKENS.some((token) => seg.includes(token)),
      );
      // 標準的な遊具名を含まない区画は「特殊遊具」とみなす(一覧表と同じ判定)。
      const isSpecial = segments.some(
        (seg) => !PLAY_STANDARD_TOKENS.some((token) => seg.includes(token)),
      );
      // 幼児用ブランコと通常のブランコを区別する。
      const hasToddlerSwing = segments.some(
        (seg) => seg.includes("幼児") && seg.includes("ブランコ"),
      );
      const hasSwing = segments.some(
        (seg) => seg.includes("ブランコ") && !seg.includes("幼児"),
      );
      const seen = new Set<string>();
      const icons: string[] = [];
      for (const def of PLAY_DEFS) {
        const matched =
          def.key === "ball"
            ? hasBall
            : def.key === "grass"
              ? hasGrass
              : def.key === "pond"
                ? hasPond
                : def.key === "toddlerSwing"
                  ? hasToddlerSwing
                  : def.key === "swing"
                    ? hasSwing
                    : def.key === "spring"
                      ? isSpring
                      : def.key === "special"
                        ? isSpecial
                        : def.tokens.some((token) => text.includes(token));
        if (!matched) continue;
        if (seen.has(def.key)) continue;
        // ヒコーキジャングルはジャングルジムの一種なので、飛があればジは出さない。
        if (def.key === "climbing" && seen.has("airplane")) continue;
        seen.add(def.key);
        icons.push(
          `<span class="park-play ${def.cls}" title="${def.title}" aria-label="${def.title}">${def.icon}</span>`,
        );
      }
      if (!icons.length) return;
      const center = centerOfLayer(lyr);
      const marker = L.marker([center.lat, center.lng], {
        icon: L.divIcon({
          className: "park-play-markers",
          html: `<span class="park-play-list">${icons.join("")}</span>`,
          iconSize: null,
          iconAnchor: [0, 0],
        }),
        riseOnHover: false,
        interactive: false,
      }).addTo(playLayer);
      markIconOwner(marker, name);
      const list = playMarkersByName.get(name) || [];
      list.push(marker);
      playMarkersByName.set(name, list);
    });

    // 公園名のラベル(高ズーム時のみ)。
    // 起動時に全件のマーカーを作ると重いので、画面内の公園だけを都度生成する。
    const escapeHtml = (value: string) =>
      value.replace(/[&<>"']/g, (ch) =>
        ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch] as string,
      );
    const parkCenters = Array.from(layersByName, ([name, lyr]) => {
      const center = centerOfLayer(lyr);
      return { name, lat: center.lat, lng: center.lng };
    });
    const parkNameLayer = L.layerGroup();
    const nameMarkers = new Map<string, any>();
    const updateParkNames = () => {
      if (map.getZoom() < 17) {
        if (nameMarkers.size) {
          nameMarkers.forEach((marker) => parkNameLayer.removeLayer(marker));
          nameMarkers.clear();
        }
        if (map.hasLayer(parkNameLayer)) map.removeLayer(parkNameLayer);
        return;
      }
      if (!map.hasLayer(parkNameLayer)) parkNameLayer.addTo(map);
      const bounds = map.getBounds().pad(0.1);
      const visible = new Set<string>();
      for (const p of parkCenters) {
        if (!bounds.contains([p.lat, p.lng])) continue;
        visible.add(p.name);
        if (nameMarkers.has(p.name)) continue;
        const marker = L.marker([p.lat, p.lng], {
          icon: L.divIcon({
            className: "park-name-marker",
            html: `<span class="park-name-label">${escapeHtml(p.name)}</span>`,
            iconSize: null,
            iconAnchor: [0, 0],
          }),
          interactive: false,
          keyboard: false,
        }).addTo(parkNameLayer);
        nameMarkers.set(p.name, marker);
      }
      nameMarkers.forEach((marker, name) => {
        if (visible.has(name)) return;
        parkNameLayer.removeLayer(marker);
        nameMarkers.delete(name);
      });
    };

    // フィルタ中は、該当しない公園の設備・遊具アイコンを隠す
    const applyIconFilter = (names: Set<string> | null) => {
      const toggle = (markersByName: Map<string, any[]>, layer: any) => {
        markersByName.forEach((markers, name) => {
          const show = !names || names.has(name);
          markers.forEach((marker) => {
            const has = layer.hasLayer(marker);
            if (show && !has) layer.addLayer(marker);
            else if (!show && has) layer.removeLayer(marker);
          });
        });
      };
      toggle(facilityMarkersByName, facilityLayer);
      toggle(playMarkersByName, playLayer);
    };

    let facilityLabelsShown = false;
    const updateFacilities = () => {
      if (map.getZoom() >= 16) {
        if (!map.hasLayer(facilityLayer)) facilityLayer.addTo(map);
      } else if (map.hasLayer(facilityLayer)) {
        map.removeLayer(facilityLayer);
      }
      if (map.getZoom() >= 16) {
        if (!map.hasLayer(playLayer)) playLayer.addTo(map);
      } else if (map.hasLayer(playLayer)) {
        map.removeLayer(playLayer);
      }
      // 公共施設の名前はもう一段ズームしたときだけ表示する(切替時のみ実行)
      const showFacilityLabels = map.getZoom() >= 15;
      if (showFacilityLabels !== facilityLabelsShown) {
        facilityLabelsShown = showFacilityLabels;
        facilityMarkers.forEach(({ layer }) => {
          if (showFacilityLabels) layer.openTooltip();
          else layer.closeTooltip();
        });
      }
    };
    map.on("zoomend", updateFacilities);
    updateFacilities();
    map.on("moveend", updateParkNames);
    updateParkNames();

    // フィルタがないときは、すべての公園を点滅させる
    allLayers.forEach((lyr) => {
      const n = lyr._parkName || "";
      lyr.setStyle(n ? MATCHED_STYLE : UNMATCHED_STYLE);
      markSelected(lyr, false);
      markBlink(lyr, true);
    });
    nearbyEntries.forEach(({ layer }) => {
      layer.setStyle(nearbyBaseStyle(layer));
      markSelected(layer, false);
      markBlink(layer, true);
    });

    let userInteracted = false;
    map.on("zoomstart dragstart", () => {
      userInteracted = true;
    });

    const fitAll = () => {
      if (userInteracted) return;
      // 初期表示は小平市の市境だけに合わせる(市外にまたがる都立公園などで広がらないように)。
      const bounds = boundaryLayer.getBounds();
      if (bounds.isValid()) {
        map.fitBounds(bounds, { padding: [20, 20], animate: false });
        return;
      }
      const parkBounds = layer.getBounds();
      if (parkBounds.isValid()) {
        map.fitBounds(parkBounds, { padding: [20, 20], animate: false });
      }
    };
    fitAll();

    // 1つの公園だけを強調表示にする(ほかは薄くする)
    const highlightOnly = (name: string) => {
      applyIconFilter(new Set([name]));
      allLayers.forEach((lyr) => {
        const parkName = lyr._parkName || "";
        if (parkName === name) {
          lyr.setStyle(SELECTED_STYLE);
          markSelected(lyr, true);
          markBlink(lyr, false);
          lyr.bringToFront?.();
        } else {
          lyr.setStyle(parkName ? DIM_STYLE : UNMATCHED_STYLE);
          markSelected(lyr, false);
          markBlink(lyr, false);
        }
      });
      nearbyEntries.forEach(({ name: nearbyName, layer: lyr }) => {
        const selected = nearbyName === name;
        lyr.setStyle(selected ? NEARBY_SELECTED_STYLE : NEARBY_DIM_STYLE);
        markSelected(lyr, selected);
        markBlink(lyr, false);
        if (selected) lyr.bringToFront?.();
      });
    };

    const focusPark = (name: string, key = "") => {
      if (key) {
        const nearbyHit = nearbyEntries.find((entry) => entry.key === key);
        if (nearbyHit) {
          const group = L.featureGroup([nearbyHit.layer]);
          map.fitBounds(group.getBounds(), { padding: [40, 40], maxZoom: 17 });
          nearbyHit.layer.openPopup?.();
          return true;
        }
      }
      const target = layersByName.get(name);
      if (target) {
        map.fitBounds(target.getBounds(), { padding: [40, 40], maxZoom: 17 });
        const targetLayer =
          typeof target.getLayers === "function" ? target.getLayers()[0] : target;
        targetLayer?.openPopup?.();
        return true;
      }
      const nearbyTargets = nearbyEntries
        .filter((entry) => entry.name === name)
        .map((entry) => entry.layer);
      if (nearbyTargets.length) {
        const group = L.featureGroup(nearbyTargets);
        map.fitBounds(group.getBounds(), { padding: [40, 40], maxZoom: 17 });
        nearbyTargets[0].openPopup?.();
        return true;
      }
      return false;
    };

    document.addEventListener("park:focus", (e: Event) => {
      const detail = (e as CustomEvent).detail || {};
      const name = detail.name;
      if (!name) return;
      const key = detail.key || "";
      if (
        !key &&
        !layersByName.has(name) &&
        !nearbyEntries.some((entry) => entry.name === name)
      )
        return;
      el.scrollIntoView({ behavior: "smooth", block: "center" });
      focusPark(name, key);
    });

    // フィルタの対象(複数ならその範囲)に地図をフォーカスする。
    let filterFocusTimer = 0;
    const focusOnParks = (names: Set<string> | null) => {
      const bounds = L.latLngBounds([]);
      const add = (lyr: any) => {
        const b = lyr?.getBounds?.();
        if (b && b.isValid()) bounds.extend(b);
      };
      if (names) {
        allLayers.forEach((lyr) => {
          if (names.has(lyr._parkName || "")) add(lyr);
        });
        nearbyEntries.forEach(({ name, layer }) => {
          if (names.has(name)) add(layer);
        });
      } else {
        allLayers.forEach(add);
      }
      if (!bounds.isValid()) return;
      map.fitBounds(bounds, { padding: [40, 40], maxZoom: 16, animate: true });
    };

    // 選択中の公園を強調するためのクラス(グロー表示)
    document.addEventListener("park:filter", (e: Event) => {
      const detail = (e as CustomEvent).detail || {};
      const names = new Set<string>(detail.names || []);
      const active = Boolean(detail.active);
      if (filterStatus) filterStatus.hidden = !active;
      const fromMap = Boolean(detail.fromMap);

      if (!fromMap && selectedBar) selectedBar.hidden = true;

      // 地図のポリゴンクリックで表を1件に絞った場合は、
      // ほかの公園のポリゴンを残したまま、選択した公園だけ強調する。
      if (fromMap) {
        allLayers.forEach((lyr) => {
          const name = lyr._parkName || "";
          if (name && names.has(name)) {
            lyr.setStyle(SELECTED_STYLE);
            markSelected(lyr, true);
            markBlink(lyr, false);
            lyr.bringToFront?.();
          } else {
            lyr.setStyle(name ? MATCHED_STYLE : UNMATCHED_STYLE);
            markSelected(lyr, false);
            markBlink(lyr, true);
          }
        });
        nearbyEntries.forEach(({ name, layer: lyr }) => {
          const selected = Boolean(name && names.has(name));
          lyr.setStyle(selected ? NEARBY_SELECTED_STYLE : nearbyBaseStyle(lyr));
          markSelected(lyr, selected);
          if (selected) lyr.bringToFront?.();
        });
        facilityMarkers.forEach(({ layer }) => {
          setFacilityOpacity(layer, true);
        });
        applyIconFilter(new Set(names));
        return;
      }

      allLayers.forEach((lyr) => {
        const name = lyr._parkName || "";
        if (!active) {
          lyr.setStyle(name ? MATCHED_STYLE : UNMATCHED_STYLE);
          markSelected(lyr, false);
          markBlink(lyr, true);
          return;
        }
        if (name && names.has(name)) {
          lyr.setStyle(SELECTED_STYLE);
          markSelected(lyr, true);
          markBlink(lyr, false);
          lyr.bringToFront?.();
        } else {
          // 該当しない公園も「すべて」のときと同じ点滅表示のままにする。
          lyr.setStyle(name ? MATCHED_STYLE : UNMATCHED_STYLE);
          markSelected(lyr, false);
          markBlink(lyr, true);
        }
      });

      nearbyEntries.forEach(({ name, layer: lyr }) => {
        if (!active) {
          lyr.setStyle(nearbyBaseStyle(lyr));
          markSelected(lyr, false);
          markBlink(lyr, true);
          return;
        }
        if (name && names.has(name)) {
          lyr.setStyle(NEARBY_SELECTED_STYLE);
          markSelected(lyr, true);
          lyr.bringToFront?.();
        } else {
          lyr.setStyle(nearbyBaseStyle(lyr));
          markSelected(lyr, false);
          markBlink(lyr, true);
        }
      });

      // 公共施設のマーカーも絞り込みに合わせて表示する。
      facilityMarkers.forEach(({ name, layer }) => {
        setFacilityOpacity(layer, !active || names.has(name));
      });
      applyIconFilter(active ? new Set(names) : null);

      // フィルタの対象にフォーカスする(キーワード入力は少し待ってから)。
      if (detail.focus) {
        const run = () => focusOnParks(active ? names : null);
        window.clearTimeout(filterFocusTimer);
        if (detail.focus === "later") {
          filterFocusTimer = window.setTimeout(run, 800);
        } else {
          run();
        }
      }
    });

    // 現在地表示(ボタン操作時のみ取得)
    const statusEl = document.querySelector<HTMLElement>("[data-locate-status]");
    const setStatus = (msg: string) => {
      if (!statusEl) return;
      statusEl.textContent = msg;
      statusEl.hidden = !msg;
    };

    let locationMarker: any = null;
    let accuracyCircle: any = null;
    let watchId: number | null = null;
    let tracking = false;
    let firstFix = true;
    let userMoved = false;
    let locateButton: HTMLButtonElement | null = null;

    const LOCATE_ICON =
      '<span aria-hidden="true"><svg viewBox="0 0 24 24" width="20" height="20"><path d="M12 2.2 20 21.5 12 16.8 4 21.5Z" fill="#1e88e5" stroke="#ffffff" stroke-width="2" stroke-linejoin="round"/></svg></span>';
    const TRACKING_ICON =
      '<span aria-hidden="true"><svg viewBox="0 0 24 24" width="20" height="20"><circle cx="12" cy="12" r="3.5" fill="currentColor"/><circle cx="12" cy="12" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span>';

    const updateLocateButton = () => {
      if (!locateButton) return;
      locateButton.classList.toggle("is-tracking", tracking);
      locateButton.setAttribute("aria-pressed", tracking ? "true" : "false");
      const label = tracking ? "現在地の追跡を停止" : "現在地を表示";
      locateButton.title = label;
      locateButton.setAttribute("aria-label", label);
      locateButton.innerHTML = tracking ? TRACKING_ICON : LOCATE_ICON;
    };

    const stopTracking = () => {
      if (watchId !== null) {
        navigator.geolocation.clearWatch(watchId);
        watchId = null;
      }
      tracking = false;
      updateLocateButton();
    };

    // ユーザーが地図を動かしたら、追従を止める(勝手に戻らないように)。
    map.on("dragstart", () => {
      if (!tracking) return;
      userMoved = true;
      stopTracking();
      setStatus(
        "地図を動かしたため、現在地の追従を停止しました。もう一度ボタンを押すと再開します。",
      );
    });

    const locate = () => {
      if (tracking) {
        stopTracking();
        setStatus("現在地の追跡を停止しました。");
        return;
      }
      if (!navigator.geolocation) {
        setStatus("このブラウザでは現在地を取得できません。");
        return;
      }
      setStatus("現在地を取得しています…");
      firstFix = true;
      const onSuccess = (pos: GeolocationPosition) => {
        const { latitude, longitude, accuracy } = pos.coords;
        if (!locationMarker) {
          const icon = L.divIcon({
            className: "park-locate-marker",
            html: '<span class="park-locate-arrow"><svg viewBox="0 0 24 24" width="24" height="24" aria-hidden="true"><path d="M12 2.2 20 21.5 12 16.8 4 21.5Z" fill="#1e88e5" stroke="#ffffff" stroke-width="2" stroke-linejoin="round"/></svg></span>',
            iconSize: [24, 24],
            iconAnchor: [12, 12],
          });
          locationMarker = L.marker([latitude, longitude], {
            icon,
            interactive: false,
            keyboard: false,
            zIndexOffset: 1000,
          }).addTo(map);
        } else {
          locationMarker.setLatLng([latitude, longitude]);
        }
        if (
          typeof pos.coords.heading === "number" &&
          Number.isFinite(pos.coords.heading)
        ) {
          const arrow = locationMarker
            .getElement()
            ?.querySelector<HTMLElement>(".park-locate-arrow");
          if (arrow) arrow.style.transform = `rotate(${pos.coords.heading}deg)`;
        }
        if (!accuracyCircle) {
          accuracyCircle = L.circle([latitude, longitude], {
            radius: Math.min(accuracy, 1000),
            color: "#1e88e5",
            weight: 1,
            fillColor: "#90caf9",
            fillOpacity: 0.15,
            interactive: false,
          }).addTo(map);
        } else {
          accuracyCircle
            .setLatLng([latitude, longitude])
            .setRadius(Math.min(accuracy, 1000));
        }
        if (firstFix) {
          map.setView([latitude, longitude], Math.max(map.getZoom(), 15));
          firstFix = false;
        } else if (!userMoved) {
          map.panTo([latitude, longitude], { animate: true, duration: 0.4 });
        }
        setStatus(
          `現在地を追跡中です(精度 約${Math.round(accuracy)}m)。もう一度押すと停止します。`,
        );
      };
      const onError = (err: GeolocationPositionError) => {
        const message =
          err.code === err.PERMISSION_DENIED
            ? "位置情報の利用が許可されていません。ブラウザの設定で許可してください。"
            : err.code === err.POSITION_UNAVAILABLE
              ? "現在地を取得できませんでした(位置情報が利用できません)。"
              : "現在地の取得がタイムアウトしました。";
        setStatus(message);
        stopTracking();
      };
      if (watchId !== null) navigator.geolocation.clearWatch(watchId);
      userMoved = false;
      tracking = true;
      updateLocateButton();
      watchId = navigator.geolocation.watchPosition(onSuccess, onError, {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 5000,
      });
    };

    const LocateControl = L.Control.extend({
      onAdd: () => {
        const btn = L.DomUtil.create("button", "park-locate") as HTMLButtonElement;
        btn.setAttribute("type", "button");
        locateButton = btn;
        L.DomEvent.disableClickPropagation(btn);
        btn.addEventListener("click", () => locate());
        updateLocateButton();
        return btn;
      },
    });
    new LocateControl({ position: "topright" }).addTo(map);

    // 位置情報の許可確認は、ボタン操作(ユーザー操作)のときだけ出す。
    // ページ読み込み時に自動で watchPosition を呼ぶと、ブラウザによっては
    // 許可ダイアログが出ずに失敗することがあるため。
    window.addEventListener("pagehide", () => {
      stopTracking();
    });

    // レイアウト確定後にサイズを再計算し、タイルを再配置する。
    const refresh = () => {
      map.invalidateSize();
      tileLayer.redraw();
      fitAll();
    };
    requestAnimationFrame(refresh);
    window.setTimeout(refresh, 300);
    window.setTimeout(refresh, 1000);
    window.addEventListener("load", refresh);
    window.addEventListener("resize", () => map.invalidateSize());
  }
</script>