aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/components/ParkMap.astro
blob: ac85c0e15a169c45edba89cdd6ff1471b9bf1768 (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
---
// 小平市の公園ポリゴン(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;
  }
  :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;
  }
  .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) {
    color: #0b57d0;
    white-space: nowrap;
  }
  .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 {
    background: #0277bd;
    border-radius: 50%;
  }
  :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) {
    background: #0277bd;
    border: 1px solid #01579b;
    border-radius: 50%;
  }
  :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 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-play-plane) {
    color: #c62828;
  }
  :global(.park-play-swing) {
    color: #ef6c00;
  }
  :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-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: "#b71c1c",
    weight: 2,
    fillColor: "#e53935",
    fillOpacity: 0.45,
  };
  const UNMATCHED_STYLE = {
    color: "#ef5350",
    weight: 1.2,
    fillColor: "#ffcdd2",
    fillOpacity: 0.3,
  };
  const DIM_STYLE = {
    color: "#ef9a9a",
    weight: 0.8,
    fillColor: "#ffebee",
    fillOpacity: 0.05,
    opacity: 0.3,
  };
  const SELECTED_STYLE = {
    color: "#7f0000",
    weight: 3,
    fillColor: "#d32f2f",
    fillOpacity: 0.6,
  };
  const NEARBY_STYLE = {
    color: "#1565c0",
    weight: 1.5,
    fillColor: "#42a5f5",
    fillOpacity: 0.25,
  };
  const NEARBY_POINT_STYLE = {
    radius: 7,
    color: "#0d47a1",
    weight: 2,
    fillColor: "#42a5f5",
    fillOpacity: 0.85,
  };
  const NEARBY_SELECTED_STYLE = {
    color: "#0d47a1",
    weight: 3,
    fillColor: "#1565c0",
    fillOpacity: 0.55,
  };
  const NEARBY_DIM_STYLE = {
    color: "#90caf9",
    weight: 0.8,
    fillColor: "#bbdefb",
    fillOpacity: 0.05,
    opacity: 0.3,
  };

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

    const map = L.map(el, {
      scrollWheelZoom: true,
      zoomSnap: 1,
      zoomDelta: 1,
      zoomAnimation: false,
      fadeAnimation: false,
      markerZoomAnimation: false,
    }).setView([35.728, 139.477], 13);

    // 帰属表示の「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 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.on(button, "click", (ev: Event) => {
          L.DomEvent.stop(ev);
          const target = map.getContainer();
          if (!document.fullscreenElement) {
            target.requestFullscreen?.().catch(() => {});
          } else {
            document.exitFullscreen?.().catch(() => {});
          }
        });
        const update = () => {
          const active = document.fullscreenElement === map.getContainer();
          button.innerHTML = active ? "✕" : "⛶";
          button.title = active ? "全画面を終了" : "全画面表示";
          button.setAttribute("aria-label", active ? "全画面を終了" : "全画面表示");
          map.invalidateSize();
        };
        document.addEventListener("fullscreenchange", update);
        return container;
      },
    });
    if (document.fullscreenEnabled) {
      new FullscreenControl({ position: "topright" }).addTo(map);
    }

    const layersByName = new Map<string, any>();
    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 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 selectedTableLink: 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 || !selectedTableLink)
        return;
      selectedNameEl.textContent = ourName;
      selectedNameEl.title =
        osmName && osmName !== ourName ? `OSM: ${osmName}` : "";
      // 表と同じく、公園名で検索する。名前がない場合だけ住所・座標を使う。
      const rec = parkDataByName.get(ourName);
      const fixed = rec?.["地図URL"];
      const name = (ourName || "").trim();
      const query = mapsQuery || (name
        ? `小平市${name}`
        : rec?.["住所"]
          ? `小平市${rec["住所"]}`
          : rec?.["緯度"] && rec?.["経度"]
            ? `${rec["緯度"]},${rec["経度"]}`
            : "小平市");
      selectedMapsLink.href =
        fixed || `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
      selectedTableLink.dataset.parkRow = encodeURIComponent(ourName);
      selectedTableLink.hidden = !listed;
      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">Googleマップ</a>' +
          '<a data-park-table-link href="#">一覧で見る</a>';
        selectedBar = box;
        selectedNameEl = box.querySelector<HTMLElement>(".park-map-selected-name");
        selectedMapsLink = box.querySelector<HTMLAnchorElement>("[data-park-maps-link]");
        selectedTableLink = box.querySelector<HTMLAnchorElement>("[data-park-table-link]");
        selectedNoteEl = box.querySelector<HTMLElement>(".park-map-selected-note");
        selectedOwnerEl = box.querySelector<HTMLElement>(".park-map-selected-owner");
        selectedTableLink?.addEventListener("click", (ev: Event) => {
          ev.preventDefault();
          const name = decodeURIComponent(
            (selectedTableLink as HTMLElement).dataset.parkRow || "",
          );
          if (name) filterName(name, true);
        });
        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.on("click", (ev: any) => {
            if (ev?.originalEvent) L.DomEvent.stopPropagation(ev.originalEvent);
            filterName(ourName, false);
            showSelected(ourName, name, true, ownerByName.get(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 });
        lyr.on("click", (ev: any) => {
          if (ev?.originalEvent) L.DomEvent.stopPropagation(ev.originalEvent);
          if (!name) return;
          filterName(name, false);
          showSelected(name, name, true, city || "市外", nearbyMapsQuery(name, city));
        });
      },
    }).addTo(map);

    // 地域センター・公民館・図書館・市役所支所・文化施設。
    // 市外の近隣施設はオレンジで表示する。
    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);
        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();
    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" aria-hidden="true"><path fill="currentColor" d="M12 2.7c-3.4 4.2-6 8.1-6 11.3a6 6 0 0 0 12 0c0-3.2-2.6-7.1-6-11.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="時計あり">⏰</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 (!icons.length) return;
      const center = centerOfLayer(lyr);
      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);
    });

    // 拡大時だけ表示する遊具アイコン。
    // 公園ポリゴンの中心に、遊具の種類を絵アイコンで表示する。
    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: "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: ["スプリング"], 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 },
    ];
    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 !== "禁止");
      if (!text && !hasBall) return;
      const seen = new Set<string>();
      const icons: string[] = [];
      for (const def of PLAY_DEFS) {
        const matched =
          def.key === "ball"
            ? hasBall
            : 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);
      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);
    });

    const updateFacilities = () => {
      if (map.getZoom() >= 16) {
        if (!map.hasLayer(facilityLayer)) facilityLayer.addTo(map);
      } else if (map.hasLayer(facilityLayer)) {
        map.removeLayer(facilityLayer);
      }
      if (map.getZoom() >= 17) {
        if (!map.hasLayer(playLayer)) playLayer.addTo(map);
      } else if (map.hasLayer(playLayer)) {
        map.removeLayer(playLayer);
      }
    };
    map.on("zoomend", updateFacilities);
    updateFacilities();

    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();

    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 });
          showSelected(
            name,
            name,
            true,
            nearbyHit.city || "市外",
            nearbyMapsQuery(name, nearbyHit.city),
          );
          return true;
        }
      }
      const target = layersByName.get(name);
      if (target) {
        map.fitBounds(target.getBounds(), { padding: [40, 40], maxZoom: 17 });
        showSelected(
          name,
          target._osmName || name,
          true,
          ownerByName.get(name) || "",
        );
        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 });
        const info = nearbyInfoByName.get(name);
        const city = String(info?.city || "").trim();
        showSelected(name, name, true, city || "市外", nearbyMapsQuery(name, city));
        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);
    });

    document.addEventListener("park:filter", (e: Event) => {
      const detail = (e as CustomEvent).detail || {};
      const names = new Set<string>(detail.names || []);
      const active = Boolean(detail.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);
          } else {
            lyr.setStyle(name ? MATCHED_STYLE : UNMATCHED_STYLE);
          }
        });
        nearbyEntries.forEach(({ name, layer: lyr }) => {
          lyr.setStyle(
            name && names.has(name) ? NEARBY_SELECTED_STYLE : nearbyBaseStyle(lyr),
          );
        });
        facilityMarkers.forEach(({ layer }) => {
          setFacilityOpacity(layer, true);
        });
        return;
      }

      allLayers.forEach((lyr) => {
        const name = lyr._parkName || "";
        if (!active) {
          lyr.setStyle(name ? MATCHED_STYLE : UNMATCHED_STYLE);
          return;
        }
        if (name && names.has(name)) {
          lyr.setStyle(MATCHED_STYLE);
        } else {
          lyr.setStyle(DIM_STYLE);
        }
      });

      nearbyEntries.forEach(({ name, layer: lyr }) => {
        if (!active) {
          lyr.setStyle(nearbyBaseStyle(lyr));
          return;
        }
        if (name && names.has(name)) {
          lyr.setStyle(nearbyBaseStyle(lyr));
        } else {
          lyr.setStyle(NEARBY_DIM_STYLE);
        }
      });

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

    // 現在地表示(ボタン操作時のみ取得)
    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 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();
    };

    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,
          }).addTo(map);
        } else {
          locationMarker.setLatLng([latitude, longitude]);
        }
        const heading =
          typeof pos.coords.heading === "number" &&
          Number.isFinite(pos.coords.heading)
            ? pos.coords.heading
            : 0;
        const arrow = locationMarker
          .getElement()
          ?.querySelector<HTMLElement>(".park-locate-arrow");
        if (arrow) arrow.style.transform = `rotate(${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;
        }
        setStatus(
          `現在地を追跡中です(精度 約${Math.round(accuracy)}m)。もう一度押すと停止します。`,
        );
      };
      const onError = () => {
        setStatus("現在地を取得できませんでした。位置情報の利用を許可してください。");
        stopTracking();
      };
      if (watchId !== null) navigator.geolocation.clearWatch(watchId);
      tracking = true;
      updateLocateButton();
      watchId = navigator.geolocation.watchPosition(onSuccess, onError, {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 30000,
      });
    };

    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>