aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/components/ParkMap.astro
blob: 1c75bee353922c53baa598fd5f6998f47512fea0 (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
---
// 小平市の公園ポリゴン(OpenStreetMap)を地図上に色塗り表示する。
// 一覧と一致した公園は赤、一致しない公園は薄い赤で表示する。
---

<div class="park-map-wrap">
  <div
    id="park-map"
    class="park-map"
    role="region"
    aria-label="小平市の公園の位置(OpenStreetMap)"
  ></div>
  <div class="park-map-legend" aria-hidden="true">
    <span><i class="swatch swatch-matched"></i>一覧と一致</span>
    <span><i class="swatch swatch-unmatched"></i>一覧にない公園・緑地</span>
    <span><i class="swatch swatch-nearby"></i>市外の近い公園(500m以内)</span>
    <span><i class="swatch swatch-facility"></i>公共施設</span>
    <span><i class="swatch swatch-boundary"></i>小平市の境界</span>
    <span><i class="swatch-fac swatch-fac-toilet">WC</i>トイレ</span>
    <span><i class="swatch-fac swatch-fac-water"><svg viewBox="0 0 24 24" width="10" height="10" 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></i>水飲み場(拡大時)</span>
  </div>
  <p class="park-map-note">
    公園の範囲を赤で表示しています。地図を拡大すると見やすくなります。PCでは地図上でスクロールするとズームできます。市外の近い公園と公共施設は別レイヤーで表示し、右上のレイヤ切替でON/OFFできます。トイレと水飲み場のアイコンは、地図を拡大すると表示されます。OpenStreetMapに公園として登録されている範囲を表示しているため、すべての公園を網羅しているわけではありません。現在地は端末内でのみ利用し、サーバーには送信しません。地図データ © <a
      href="https://www.openstreetmap.org/copyright"
      target="_blank"
      rel="noopener">OpenStreetMap</a
    > contributors
  </p>
  <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-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) {
    width: 34px;
    height: 34px;
    border: 0;
    background: #fff;
    color: #1e88e5;
    font-size: 20px;
    line-height: 1;
    cursor: pointer;
  }
  :global(.park-locate:hover) {
    background: #f0f7ff;
  }
  .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 svg) {
    display: block;
  }
  /* 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 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_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 ? `${city}${name}` : name) : "";
    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 name = (ourName || "").trim();
      const query = mapsQuery || (name
        ? `小平市${name}`
        : rec?.["住所"]
          ? `小平市${rec["住所"]}`
          : rec?.["緯度"] && rec?.["経度"]
            ? `${rec["緯度"]},${rec["経度"]}`
            : "小平市");
      selectedMapsLink.href = `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) layersByName.set(ourName, lyr);

        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, {
      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 || ""}`;
        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();
    (facilities as any[]).forEach((f) => {
      if (f.lat == null || f.lon == null) return;
      L.circleMarker([f.lat, f.lon], {
        radius: 6,
        color: "#4a148c",
        weight: 1.5,
        fillColor: "#8e24aa",
        fillOpacity: 0.85,
      })
        .bindPopup(
          `<strong>${f.name}</strong><br>${f.type}<br>${f.hours || ""}${f.closed ? `<br>休: ${f.closed}` : ""}<br>トイレ: ${f.toilet || "未確認"} / 給水: ${f.water || "未確認"}`,
        )
        .addTo(publicFacilityLayer);
    });
    publicFacilityLayer.addTo(map);

    L.control
      .layers(
        null,
        {
          "市外の近い公園(500m以内)": nearbyLayer,
          "公共施設": publicFacilityLayer,
        },
        { collapsed: false, position: "topright" },
      )
      .addTo(map);

    // 拡大時だけ表示する設備アイコン(トイレ・水飲み場)
    // 一覧と一致した公園のポリゴン内にだけ表示する。
    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>',
        );
      }
      if (!icons.length) return;
      const center = lyr.getBounds().getCenter();
      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 updateFacilities = () => {
      if (map.getZoom() >= 16) {
        if (!map.hasLayer(facilityLayer)) facilityLayer.addTo(map);
      } else if (map.hasLayer(facilityLayer)) {
        map.removeLayer(facilityLayer);
      }
    };
    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) {
          map.fitBounds(nearbyHit.layer.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);
      const visible: any[] = [];

      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 : NEARBY_STYLE);
        });
        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);
          visible.push(lyr);
        } else {
          lyr.setStyle(DIM_STYLE);
        }
      });

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

      if (active && visible.length && visible.length < 30) {
        const bounds = L.featureGroup(visible).getBounds();
        if (bounds.isValid()) {
          map.fitBounds(bounds, { padding: [40, 40], maxZoom: 16 });
        }
      }
    });

    // 現在地表示(スマホでは自動で取得を試みる)
    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;

    const locate = (center = false) => {
      if (!navigator.geolocation) {
        setStatus("このブラウザでは現在地を取得できません。");
        return;
      }
      setStatus("現在地を取得しています…");
      const onSuccess = (pos: GeolocationPosition) => {
        const { latitude, longitude, accuracy } = pos.coords;
        if (!locationMarker) {
          locationMarker = L.circleMarker([latitude, longitude], {
            radius: 7,
            color: "#ffffff",
            weight: 2,
            fillColor: "#1e88e5",
            fillOpacity: 1,
          }).bindPopup("現在地", { autoPan: false });
          locationMarker.on("add", () => {
            locationMarker.getElement()?.setAttribute("data-locate", "true");
          });
          locationMarker.addTo(map);
        } else {
          locationMarker.setLatLng([latitude, longitude]);
        }
        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));
        }
        setStatus(`現在地を表示しています(精度 約${Math.round(accuracy)}m)。`);
        if (center) map.setView([latitude, longitude], Math.max(map.getZoom(), 15));
      };
      const onError = () => {
        setStatus("現在地を取得できませんでした。位置情報の利用を許可してください。");
      };
      if (watchId !== null) navigator.geolocation.clearWatch(watchId);
      watchId = navigator.geolocation.watchPosition(onSuccess, onError, {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 30000,
      });
    };

    const LocateControl = L.Control.extend({
      onAdd: () => {
        const btn = L.DomUtil.create("button", "leaflet-bar park-locate");
        btn.setAttribute("type", "button");
        btn.title = "現在地を表示";
        btn.setAttribute("aria-label", "現在地を表示");
        btn.innerHTML = '<span aria-hidden="true">◎</span>';
        L.DomEvent.disableClickPropagation(btn);
        btn.addEventListener("click", () => locate(true));
        return btn;
      },
    });
    new LocateControl({ position: "topright" }).addTo(map);

    if (window.matchMedia("(max-width: 640px)").matches) {
      locate(true);
    }
    window.addEventListener("pagehide", () => {
      if (watchId !== null) navigator.geolocation.clearWatch(watchId);
    });

    // レイアウト確定後にサイズを再計算し、タイルを再配置する。
    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>