aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/components/ParkMap.astro
blob: 8fdf5bfc48f6b92c93e4a8095d6e385a6a847310 (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
---
// 小平市の公園ポリゴン(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-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">
    公園の範囲を赤で表示しています。地図を拡大すると見やすくなります。トイレと水飲み場のアイコンは、地図を拡大すると表示されます。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-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-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-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 がタイルに付くと行が16pxずれるため、0にする。 */
  .park-map :global(.leaflet-tile) {
    margin: 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/kodaira-parks-osm.json";
  import boundary from "@/data/kodaira-boundary.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 el = document.getElementById("park-map");
  if (el && !el.dataset.initialized) {
    el.dataset.initialized = "1";

    const map = L.map(el, {
      scrollWheelZoom: false,
      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 layersByName = new Map<string, any>();
    const allLayers: any[] = [];
    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 === "東京都"
        ? "都立"
        : 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 = "",
    ) => {
      if (!selectedBar || !selectedNameEl || !selectedMapsLink || !selectedTableLink)
        return;
      selectedNameEl.textContent = ourName;
      selectedNameEl.title =
        osmName && osmName !== ourName ? `OSM: ${osmName}` : "";
      // 名前が「緑地(OSM …)」のような場合は名前検索が使えないため、
      // 座標があれば緯度経度で開く。
      const rec = parkDataByName.get(ourName);
      const lat = rec?.["緯度"];
      const lng = rec?.["経度"];
      selectedMapsLink.href =
        lat && lng
          ? `https://www.google.com/maps/search/?api=1&query=${lat},${lng}`
          : "https://www.google.com/maps/search/?api=1&query=" +
            encodeURIComponent(`小平市${ourName}`);
      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, {
      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", () => {
            filterName(ourName, false);
            showSelected(ourName, name, true, ownerByName.get(ourName) || "");
          });
        } else if (p.name) {
          // 一覧にないOSM上の公園・緑地。名前があればバーに表示する。
          lyr.on("click", () => showSelected(name, name, false));
        } 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);

    // 拡大時だけ表示する設備アイコン(トイレ・水飲み場)
    // 一覧と一致した公園のポリゴン内にだけ表示する。
    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,
      }).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) => {
      const target = layersByName.get(name);
      if (!target) return false;
      map.fitBounds(target.getBounds(), { padding: [40, 40], maxZoom: 17 });
      showSelected(
        name,
        target._osmName || name,
        true,
        ownerByName.get(name) || "",
      );
      return true;
    };

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

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

      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>