-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
972 lines (813 loc) · 35.5 KB
/
index.html
File metadata and controls
972 lines (813 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
<!DOCTYPE html>
<html lang="ja" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>アメダスマップ | 全国のアメダスデータを可視化</title>
<meta name="version" content="2.0.0-alpha.2" />
<!-- SEO Meta Tags -->
<meta name="description" content="気象庁のアメダスデータを利用して、日本全国の現在の気温、降水量、風速、積雪深、湿度を地図上に可視化するWebアプリケーションです。">
<meta name="keywords" content="アメダス, 天気, 気象庁, 気温, 降水量, 風速, 積雪深, 湿度, 可視化, マップ">
<meta name="author" content="Genbu Hase">
<meta name="robots" content="index, follow">
<!-- Open Graph Protocol (OGP) -->
<meta property="og:title" content="アメダスマップ | 全国のアメダスデータを可視化">
<meta property="og:type" content="website">
<meta property="og:url" content="https://genbuhase.github.io/AMeDAS_Visualizer/">
<!-- <meta property="og:image" content="https://genbuhase.github.io/ogp-image.png"> TODO: OGP画像のURLに変更 -->
<meta property="og:description" content="気象庁のアメダスデータを利用して、日本全国の現在の気象状況(気温、降水量など)を地図上に可視化するWebアプリケーションです。">
<meta property="og:site_name" content="アメダスマップ">
<meta property="og:locale" content="ja_JP">
<!-- Twitter Cards -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="アメダスマップ">
<meta name="twitter:description" content="日本全国のアメダスデータ(気温、降水量、積雪深など)をリアルタイムで地図上に表示します。">
<!-- <meta name="twitter:image" content="https://genbuhase.github.io/ogp-image.png"> TODO: OGP画像のURLに変更 -->
<!-- Icons (Placeholders) -->
<!-- <link rel="icon" href="/favicon.ico"> TODO: faviconの画像に変更 -->
<!-- <link rel="apple-touch-icon" href="/apple-touch-icon.png"> TODO: faviconの画像に変更 -->
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha512-BwHfrr4c9kmRkLw6iXFdzcdWV/PGkVgiIyIWLLlTSXzWQzxuSg4DiQUCpauz/EWjgk5TYQqX/kvn9pG1NpYfqg==" crossorigin="anonymous"></script>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha512-Zcn6bjR/8RZbLEpLIeOwNtzREBAJnUKESxces60Mpoj+2okopSAcSUIUOseddDm0cxnGQzxIR7vJgsLZbdLE3w==" crossorigin="anonymous">
<!-- Tailwind CSS (for styling) -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
body,
html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: "Noto Sans JP", sans-serif;
overflow: hidden; /* スマホでのバウンス防止 */
}
#map {
height: 100%;
width: 100%;
z-index: 1;
}
/* パネルのz-index設定 */
.info-panel {
z-index: 1000;
}
.panel-header {
background: rgba(255, 255, 255, 0.98);
backdrop-filter: blur(4px);
}
.panel-body {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(4px);
/* 高さ制限はTailwindクラスで行うため削除 */
}
.legend-item {
display: flex;
align-items: center;
margin-bottom: 4px;
font-size: 0.8rem;
}
.legend-color {
width: 16px;
height: 16px;
border-radius: 50%;
margin-right: 8px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
/* 積雪量ラベル (お気に入り用) - カスタムスタイル */
.fav-label {
background: transparent !important;
border: none !important;
box-shadow: none !important;
}
/* 吹き出しの矢印を消す */
.fav-label:before {
display: none !important;
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #bbb;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #999;
}
</style>
</head>
<body>
<!-- オーバーレイ -->
<aside id="info-panel" class="absolute top-4 left-4 right-4 md:right-auto md:w-96 info-panel rounded-lg shadow-xl overflow-hidden transition-all duration-300 flex flex-col max-h-[calc(100dvh-2rem)]">
<!-- パネルヘッダー -->
<header class="panel-header p-4 flex justify-between items-center cursor-pointer border-b border-gray-100 hover:bg-gray-50 transition-colors flex-none" onclick="togglePanel()">
<h1 class="text-xl font-bold text-gray-800 m-0">🗾 アメダスマップ</h1>
<button id="panel-toggle-icon" class="text-gray-500 hover:text-gray-700 font-bold transform transition-transform duration-300 p-1">
▼
</button>
</header>
<!-- パネルコンテンツ -->
<article id="panel-body" class="panel-body p-4 pt-2 flex-1 overflow-y-auto overscroll-contain">
<!-- ビュー切り替えタブ -->
<div class="flex border-b border-gray-200">
<div id="tab-all" onclick="event.stopPropagation(); switchMode(false)" class="flex-1 py-2 text-sm font-bold text-center cursor-pointer transition-colors border-b-2 border-blue-600 text-blue-600">📌 すべての地点</div>
<div id="tab-fav" onclick="event.stopPropagation(); switchMode(true)" class="flex-1 py-2 text-sm font-bold text-center cursor-pointer transition-colors border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50">⭐️ お気に入り</div>
</div>
<!-- 観測日時 -->
<div class="pt-4">
<h2 class="text-sm font-bold text-gray-700 mb-2">📅 観測日時</h2>
<p id="data-time" class="text-lg font-mono text-gray-900">----/--/-- --:--</p>
</div>
<!-- データ種類選択 -->
<div class="pt-4">
<h2 class="text-sm font-bold text-gray-700 mb-2">📊 データ種類</h2>
<select id="dataTypeSelect" class="w-full p-2 border border-gray-300 rounded shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500" onchange="changeDataType(this.value)">
<option value="temp" selected>🌡️ 気温</option>
<option value="precipitation1h">☔ 降水量(1時間)</option>
<option value="wind">🍃 風速</option>
<option value="snow">⛄️ 積雪深</option>
<option value="humidity">💧 湿度</option>
</select>
</div>
<!-- ランキング/お気に入りリスト -->
<div id="ranking-container" class="pt-4 pb-4">
<!-- JSで動的に挿入 -->
</div>
<!-- 凡例 -->
<div class="border-t pt-4">
<h2 class="text-sm font-bold text-gray-700 mb-2">凡例</h2>
<div id="legend" class="grid grid-cols-2 gap-2">
<!-- JSで動的に挿入 -->
</div>
</div>
<div class="border-t mt-4 pt-4 text-xs text-gray-500">
データ出典: <a href="https://www.jma.go.jp/" target="_blank" class="underline hover:text-blue-600">気象庁</a>
</div>
<button onclick="event.stopPropagation(); loadData()" class="mt-4 w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded transition duration-200 shadow hover:shadow-md">
データを更新
</button>
</article>
</aside>
<!-- Map Container -->
<main id="map"></main>
<script>
// --- 設定 ---
const PROXY_URL = 'https://corsproxy.io/?';
const JMA_TILE_BASE = 'https://www.jma.go.jp/bosai/jmatile/data/snow';
const MAP_CENTER = [38.0, 137.0];
const MAP_ZOOM = 6;
const STORAGE_KEY = 'amedas_favorites';
// URLパラメータからテストモード判定
const urlParams = new URLSearchParams(window.location.search);
const TEST_MODE = urlParams.get('test') === 'true';
// --- データ定義 ---
const DATA_TYPES = {
temp: {
name: '気温',
unit: '℃',
icon: '🌡️',
jmaElemCode: 'temp',
colors: [
{ min: 35, color: '#960018', label: '35℃ ~' },
{ min: 30, color: '#ff2800', label: '30℃ ~' },
{ min: 25, color: '#ff9900', label: '25℃ ~' },
{ min: 20, color: '#f2f200', label: '20℃ ~' },
{ min: 15, color: '#00ff00', label: '15℃ ~' },
{ min: 10, color: '#00cfff', label: '10℃ ~' },
{ min: 5, color: '#0041ff', label: '5℃ ~' },
{ min: 0, color: '#218cff', label: '0℃ ~' },
{ min: -100, color: '#a0d2ff', label: '0℃ 未満' }
],
sortDesc: true
},
precipitation1h: {
name: '降水量(1時間)',
unit: 'mm',
icon: '🌧️',
jmaElemCode: 'precipitation1h',
colors: [
{ min: 80, color: '#b40068', label: '80mm ~' },
{ min: 50, color: '#ff2800', label: '50mm ~' },
{ min: 30, color: '#ff9900', label: '30mm ~' },
{ min: 20, color: '#f2f200', label: '20mm ~' },
{ min: 10, color: '#218cff', label: '10mm ~' },
{ min: 5, color: '#0041ff', label: '5mm ~' },
{ min: 1, color: '#a0d2ff', label: '1mm ~' },
{ min: 0, color: '#cccccc', label: '0mm' }
],
sortDesc: true
},
wind: {
name: '風速',
unit: 'm/s',
icon: '💨',
jmaElemCode: 'wind',
colors: [
{ min: 25, color: '#ff0000', label: '25m/s ~' },
{ min: 20, color: '#ff5500', label: '20m/s ~' },
{ min: 15, color: '#ff9900', label: '15m/s ~' },
{ min: 10, color: '#f2f200', label: '10m/s ~' },
{ min: 5, color: '#00cf00', label: '5m/s ~' },
{ min: 3, color: '#00ff7f', label: '3m/s ~' },
{ min: 0, color: '#cccccc', label: '0m/s ~' }
],
sortDesc: true
},
snow: {
name: '積雪深',
unit: 'cm',
icon: '⛄',
jmaElemCode: 'snow',
colors: [
{ min: 200, color: '#e600ab', label: '200cm ~' },
{ min: 150, color: '#ff2800', label: '150cm ~' },
{ min: 100, color: '#ff9900', label: '100cm ~' },
{ min: 50, color: '#f2f200', label: '50cm ~' },
{ min: 20, color: '#0041ff', label: '20cm ~' },
{ min: 5, color: '#218cff', label: '5cm ~' },
{ min: 1, color: '#a0d2ff', label: '1cm ~' },
{ min: 0, color: '#cccccc', label: '0cm' }
],
sortDesc: true
},
humidity: {
name: '湿度',
unit: '%',
icon: '💧',
jmaElemCode: 'humidity',
colors: [
{ min: 90, color: '#0041ff', label: '90% ~' },
{ min: 70, color: '#00cfff', label: '70% ~' },
{ min: 50, color: '#00ff00', label: '50% ~' },
{ min: 30, color: '#f2f200', label: '30% ~' },
{ min: 0, color: '#ff9900', label: '0% ~' }
],
sortDesc: true
}
};
// --- マップ初期化 ---
const map = L.map('map', { zoomControl: false }).setView(MAP_CENTER, MAP_ZOOM);
L.control.zoom({ position: 'bottomright' }).addTo(map);
// 地理院地図 (淡色地図)
L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png', {
attribution: "<a href='https://maps.gsi.go.jp/development/ichiran.html' target='_blank'>地理院タイル</a>",
maxZoom: 18,
minZoom: 5
}).addTo(map);
let geoJsonLayer = null;
let currentGeoData = null; // 取得したアメダスデータまたはGeoJSONデータ(積雪深)
let isFavoriteMode = false; // お気に入り表示モードかどうか
let currentPopupCode = null; // 再描画時にポップアップを復元するための変数
let currentDataType = 'temp'; // 現在選択されているデータ種類
let amedasStations = null; // 観測所データ(amedastable.json)
// --- 凡例の生成 ---
const legendContainer = document.getElementById('legend');
function updateLegend() {
legendContainer.innerHTML = '';
const typeConfig = DATA_TYPES[currentDataType];
if (!typeConfig) return;
typeConfig.colors.forEach(item => {
const div = document.createElement('div');
div.className = 'legend-item';
// 0の時など特定条件で枠線をつける
const borderStyle = (item.min === 0 || item.label.includes('0mm')) ? 'border: 1px solid #999;' : '';
div.innerHTML = `<div class="legend-color" style="background:${item.color}; ${borderStyle}"></div><span>${item.label}</span>`;
legendContainer.appendChild(div);
});
}
// 初期表示
updateLegend();
// --- データ種類変更 ---
function changeDataType(type) {
if (currentDataType === type) return;
currentDataType = type;
updateLegend();
loadData(); // データを再取得・再描画
}
// --- UI パネル制御 ---
function togglePanel() {
const body = document.getElementById('panel-body');
const icon = document.getElementById('panel-toggle-icon');
const panel = document.getElementById('info-panel');
if (body.style.display === 'none') {
body.style.display = 'block';
icon.style.transform = 'rotate(0deg)'; // 元に戻す
panel.style.height = 'auto';
} else {
body.style.display = 'none';
icon.style.transform = 'rotate(-90deg)'; // 横向きにする
panel.style.height = 'auto';
}
}
// --- LocalStorage / お気に入り機能 ---
function getFavorites() {
try {
// 文字列型として取得・保存を統一する
return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]').map(String);
} catch {
return [];
}
}
function isFavorite(code) {
return getFavorites().includes(String(code));
}
// グローバル関数として公開 (ポップアップから呼ぶため)
window.toggleFavorite = function (code) {
const strCode = String(code); // 型を文字列に統一
let favs = getFavorites();
let isFavNow = false;
if (favs.includes(strCode)) {
favs = favs.filter(c => c !== strCode);
isFavNow = false;
} else {
favs.push(strCode);
isFavNow = true;
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(favs));
// 再描画を行う (スタイルの即時反映のため)
// ポップアップが閉じてしまわないよう、currentPopupCode をセットして renderMap で復元する
currentPopupCode = strCode;
renderMap();
};
// --- モード切替 ---
window.switchMode = function (toFavoriteMode) {
isFavoriteMode = toFavoriteMode;
const tabAll = document.getElementById('tab-all');
const tabFav = document.getElementById('tab-fav');
const activeClass = "flex-1 py-2 text-sm font-bold text-center cursor-pointer transition-colors border-b-2 border-blue-600 text-blue-600";
const inactiveClass = "flex-1 py-2 text-sm font-bold text-center cursor-pointer transition-colors border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50";
if (isFavoriteMode) {
tabAll.className = inactiveClass;
tabFav.className = activeClass;
} else {
tabAll.className = activeClass;
tabFav.className = inactiveClass;
}
renderMap();
};
// --- ユーティリティ ---
// 値のフォーマット
function formatValue(val) {
if (val === null || val === undefined) return '-';
return val.toLocaleString();
}
// 観測所プロパティから現在のモードの値を取得
function getValue(props) {
if (!props) return null;
let val = null;
// 積雪深モード (GeoJSON由来またはJSON由来)
if (currentDataType === 'snow') {
// GeoJSON (jmatile) 由来の場合
if (props.snowd !== undefined) val = props.snowd;
// JSON (amedas/map) 由来の場合
else if (props.snow !== undefined) val = props.snow;
else if (props.val !== undefined) val = props.val;
} else {
// その他のモード (JSON由来)
val = props[currentDataType];
}
// 値がない場合 (undefined, null)
if (val === undefined || val === null) return null;
// 配列の場合(JSON由来の一部)は[値, フラグ]
if (Array.isArray(val)) {
val = val[0];
}
const num = parseFloat(val);
return isNaN(num) ? null : num;
}
// 色を取得
function getColor(val) {
const typeConfig = DATA_TYPES[currentDataType];
if (val === null || val === undefined) return '#ccc';
// colors 配列を上から見て条件に合うものを返す
const config = typeConfig.colors.find(c => val >= c.min);
return config ? config.color : '#ccc';
}
// ズームレベルに応じた半径計算
function calcRadius(zoom, val) {
if (val === null || val === undefined) val = 0;
// 0値地点は見やすくするため最小半径を確保
if (val <= 0) return zoom < 7 ? 3 : 5;
// 基礎サイズ: ズームレベルが高いほど大きく
let baseSize = (zoom - 4) * 1.2;
if (baseSize < 2) baseSize = 2;
// 値による補正 (積雪深以外でも大きくしすぎないように調整)
let factor = 0;
if (val > 0) {
factor = Math.sqrt(val) * 0.5;
// 積雪深などで値が大きい場合のキャップ的な調整
if (currentDataType === 'snow' && val > 200) {
factor += (val - 200) * 0.05;
}
}
return baseSize + factor;
}
// UTC文字列(YYYYMMDDHHmm)をJST文字列(YYYY/MM/DD HH:mm)に変換
function formatUtcToJst(dateStr) {
if (!dateStr || dateStr.length < 12) return "--/-- --:--";
const year = parseInt(dateStr.substring(0, 4), 10);
const month = parseInt(dateStr.substring(4, 6), 10) - 1;
const day = parseInt(dateStr.substring(6, 8), 10);
const hour = parseInt(dateStr.substring(8, 10), 10);
const min = parseInt(dateStr.substring(10, 12), 10);
const utcDate = new Date(Date.UTC(year, month, day, hour, min));
const JST_OFFSET = 9 * 60 * 60 * 1000;
const jstDate = new Date(utcDate.getTime() + JST_OFFSET);
const y = jstDate.getUTCFullYear();
const m = String(jstDate.getUTCMonth() + 1).padStart(2, '0');
const d = String(jstDate.getUTCDate()).padStart(2, '0');
const h = String(jstDate.getUTCHours()).padStart(2, '0');
const mi = String(jstDate.getUTCMinutes()).padStart(2, '0');
return `${y}/${m}/${d} ${h}:${mi}`;
}
// --- データ取得ロジック ---
async function fetchWithProxy(url) {
if (TEST_MODE) {
// テストモード時はプロキシを通さず直接取得 (ローカルサーバ等を想定)
console.log(`[Test Mode] Fetching: ${url}`);
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
}
try {
const targetUrl = PROXY_URL + encodeURIComponent(url);
const response = await fetch(targetUrl);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
} catch (e) {
console.error("Fetch failed (Proxy):", e);
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.json();
} catch (e2) {
throw new Error(`データ取得エラー: ${e.message}`);
}
}
}
// アメダス観測所一覧の取得
async function fetchStations() {
if (amedasStations) return amedasStations;
const url = TEST_MODE
? './test_data/amedastable.json'
: 'https://www.jma.go.jp/bosai/amedas/const/amedastable.json';
try {
amedasStations = await fetchWithProxy(url);
return amedasStations;
} catch (e) {
console.error("Failed to fetch station list:", e);
throw e;
}
}
// 最新時刻の取得 (その他のデータ用)
async function getLatestAmedasTime() {
const url = TEST_MODE
? './test_data/latest_time.txt'
: 'https://www.jma.go.jp/bosai/amedas/data/latest_time.txt';
try {
if (TEST_MODE) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const text = await response.text();
return new Date(text.trim());
}
// テキストデータを取得 (例: 2024-01-01T12:00:00+09:00)
const response = await fetch(PROXY_URL + encodeURIComponent(url));
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const text = await response.text();
return new Date(text.trim()); // Dateオブジェクトを返す
} catch (e) {
console.error("最新時刻取得エラー:", e);
throw e;
}
}
// 全国データの取得 (JSON形式)
async function fetchAmedasMapData(dateObj) {
if (TEST_MODE) {
return await fetchWithProxy('./test_data/map_data.json');
}
// YYYYMMDDHHmmss形式に変換
const pad = (n) => n.toString().padStart(2, '0');
const yyyy = dateObj.getFullYear();
const mm = pad(dateObj.getMonth() + 1);
const dd = pad(dateObj.getDate());
const hh = pad(dateObj.getHours());
const mi = pad(Math.floor(dateObj.getMinutes() / 10) * 10); // 10分単位に丸める
const ss = '00';
const timeStr = `${yyyy}${mm}${dd}${hh}${mi}${ss}`;
const url = `https://www.jma.go.jp/bosai/amedas/data/map/${timeStr}.json`;
return await fetchWithProxy(url);
}
async function getLatestSnowTimeData() {
const url = TEST_MODE
? './test_data/targetTimes.json'
: `${JMA_TILE_BASE}/targetTimes.json`;
try {
const data = await fetchWithProxy(url);
if (!Array.isArray(data)) throw new Error("targetTimes is not an array");
const latestValid = data.find(item =>
item.elements && item.elements.includes("amds_snowd")
);
if (latestValid) return latestValid;
throw new Error("Valid snow data (amds_snowd) not found in targetTimes");
} catch (e) {
console.error(e);
throw new Error("最新時刻情報の取得に失敗しました。");
}
}
map.on('zoomend', function () {
if (!geoJsonLayer) return;
const currentZoom = map.getZoom();
geoJsonLayer.eachLayer(function (layer) {
if (layer.feature && layer.feature.properties) {
const val = getValue(layer.feature.properties);
layer.setRadius(calcRadius(currentZoom, val));
}
});
});
// マップ描画関数
function renderMap() {
if (!currentGeoData) return;
if (geoJsonLayer) {
map.removeLayer(geoJsonLayer);
}
const favs = getFavorites();
geoJsonLayer = L.geoJSON(currentGeoData, {
filter: function (feature) {
const props = feature.properties || {};
const val = getValue(props);
// 値がない、または無効な値の場合は表示しない
if (val === null || val === undefined) return false;
// 積雪深の場合の欠測値除外 (既存互換)
if (currentDataType === 'snow' && val === 32767) return false;
if (isFavoriteMode) {
return favs.includes(String(props.code));
}
return true;
},
pointToLayer: function (feature, latlng) {
const props = feature.properties || {};
const val = getValue(props);
let color = getColor(val);
let opacity = 0.8;
let borderColor = '#fff';
let weight = 1;
let radius = calcRadius(map.getZoom(), val);
if (!val) {
color = '#cccccc'; // グレーに変更
borderColor = '#666'; // 少し濃い枠線
opacity = 1.0;
}
// お気に入り強調
const isFav = isFavorite(props.code);
if (isFav) {
borderColor = '#ff0000'; // 赤枠
weight = 2; // 太枠
opacity = 1.0;
}
const marker = L.circleMarker(latlng, {
radius: radius,
fillColor: color,
color: borderColor,
weight: weight,
opacity: opacity,
fillOpacity: opacity
});
// ポップアップの設定
let unit = DATA_TYPES[currentDataType].unit;
let label = DATA_TYPES[currentDataType].name;
let elemCode = DATA_TYPES[currentDataType].jmaElemCode || 'snow';
// 地点名解決
const nameJP = props.nameJP || props.kjName || props.name || "地点";
const nameKana = props.nameKana || props.knName || "";
let displayName = nameJP;
let subName = nameKana;
if (!displayName || displayName === "地点") {
displayName = props.code || "地点";
subName = "";
}
let graphLinkHtml = "";
let favBtnHtml = "";
const code = props.code;
if (code) {
const jmaGraphUrl = `https://www.jma.go.jp/bosai/amedas/#amdno=${code}&format=graph&elem=${elemCode}`;
graphLinkHtml = `
<a
href="${jmaGraphUrl}" target="_blank" rel="noopener noreferrer"
class="flex-1 bg-white hover:bg-blue-50 text-blue-600 border border-blue-600 text-sm font-bold py-2 px-3 rounded text-center transition no-underline flex items-center justify-center" style="color: #2563eb !important; text-decoration: none !important;">
📊 推移グラフ
</a>
`;
const btnText = isFav ? '★ 解除' : '☆ お気に入り';
const btnClass = isFav
? "flex-1 bg-yellow-50 text-yellow-700 border border-yellow-300 text-sm font-bold py-2 px-3 rounded cursor-pointer hover:bg-yellow-100 transition flex items-center justify-center"
: "flex-1 bg-white text-gray-600 border border-gray-300 text-sm font-bold py-2 px-3 rounded cursor-pointer hover:bg-gray-50 transition flex items-center justify-center";
favBtnHtml = `
<button onclick="toggleFavorite('${code}')" class="${btnClass}">
${btnText}
</button>
`;
// お気に入り地点の場合のTooltip (強調表示)
if (isFav && val !== null) {
const tooltipHtml = `
<div style="background-color: ${color}; color: #fff; padding: 2px 6px; border-radius: 4px; font-weight: bold; font-size: 12px; text-shadow: 0 0 2px #000;">
${formatValue(val)}${unit}
</div>
`;
marker.bindTooltip(tooltipHtml, { permanent: true, direction: 'right', offset: [8, 0], className: 'fav-label', opacity: 1 });
}
}
let popupContent = `
<div class="font-sans min-w-[240px]">
<div class="font-bold text-lg mb-1">${displayName}</div>
${subName ? `<div class="text-xs text-gray-600 mb-1">${subName}</div>` : ''}
<hr class="my-2 border-gray-300">
<div class="mb-3">
<span class="text-sm text-gray-600">${label}:</span>
<span class="font-bold text-2xl ml-1" style="color:${color}">${formatValue(val)}</span>
<span class="text-sm ml-1">${unit}</span>
</div>
<div class="flex gap-2">
${graphLinkHtml}
${favBtnHtml}
</div>
</div>
`;
marker.bindPopup(popupContent, { minWidth: 240 });
// ポップアップ復元
if (currentPopupCode && String(props.code) === String(currentPopupCode)) {
setTimeout(() => marker.openPopup(), 100);
currentPopupCode = null;
}
return marker;
}
}).addTo(map);
updateRankingList();
}
// --- リスト表示機能 ---
function updateRankingList() {
const container = document.getElementById('ranking-container');
container.innerHTML = '';
if (!currentGeoData || !currentGeoData.features) return;
const typeConfig = DATA_TYPES[currentDataType];
// データ抽出と整形
let items = currentGeoData.features.map(f => {
const props = f.properties;
const val = getValue(props);
// 地点名解決
const nameJP = props.nameJP || props.kjName || props.name || "地点";
const code = String(props.code);
return {
code: code,
name: nameJP,
val: val,
lat: f.geometry.coordinates[1], // GeoJSONは [lon, lat]
lon: f.geometry.coordinates[0]
};
}).filter(item => {
const val = item.val;
if (val === null || val === undefined) return false;
if (currentDataType === 'snow' && val === 32767) return false;
return true;
});
// 並び替え (降順/昇順)
items.sort((a, b) => {
if (typeConfig.sortDesc) return b.val - a.val;
return a.val - b.val;
});
// 表示アイテムの選定
let displayItems = [];
let title = "";
if (isFavoriteMode) {
const favs = getFavorites();
displayItems = items.filter(item => favs.includes(item.code));
title = `⭐️ お気に入り地点`;
if (displayItems.length === 0) {
container.innerHTML = `<h3 class="text-sm font-bold text-gray-700 mb-2">${title}</h3><div class="text-sm text-gray-500 text-center py-2 bg-gray-50 rounded">登録がありません</div>`;
return;
}
} else {
displayItems = items.slice(0, 10); // Top 10
title = `🏆️ ${typeConfig.name}ランキング`;
}
// HTML生成
let html = `<h3 class="text-sm font-bold text-gray-700 mb-2">${title}</h3><ul class="text-sm space-y-1 max-h-60 overflow-y-auto pr-1">`;
displayItems.forEach((item, index) => {
const rankStr = `<span class="inline-block w-5 text-center font-bold text-gray-500 mr-1">${index + 1}.</span>`;
const color = getColor(item.val);
html += `
<li class="flex justify-between items-center p-2 hover:bg-gray-100 rounded cursor-pointer transition-colors" onclick="flyToPoint(${item.lat}, ${item.lon}, '${item.code}')">
<div class="truncate flex-1 flex items-center">
${rankStr}
<span class="font-medium text-gray-800 truncate">${item.name}</span>
</div>
<div class="font-bold whitespace-nowrap ml-2" style="color:${color}">
${formatValue(item.val)} <span class="text-xs text-black">${typeConfig.unit}</span>
</div>
</li>
`;
});
html += '</ul>';
container.innerHTML = html;
}
// 地点へ移動してポップアップを開く
window.flyToPoint = function (lat, lon, code) {
map.flyTo([lat, lon], 12, { duration: 1.5 });
// ポップアップを開くために少し待つ (移動完了後)
setTimeout(() => {
if (geoJsonLayer) {
geoJsonLayer.eachLayer(layer => {
const props = layer.feature.properties || {};
if (String(props.code) === String(code)) {
layer.openPopup();
}
});
}
}, 1600);
};
window.loadData = async function () {
// 観測所データがなければ取得
try {
await fetchStations();
} catch (e) {
alert("観測所データの取得に失敗しました。");
return;
}
// 読み込み中表示
document.getElementById('data-time').textContent = '読み込み中...';
const container = document.getElementById('ranking-container');
container.innerHTML = '<div class="text-center text-gray-500 py-4">読み込み中...</div>';
try {
if (currentDataType === 'snow') {
// 積雪深: 既存のGeoJSON APIを使用
const targetTime = await getLatestSnowTimeData();
const validTime = targetTime.validtime; // GMT
const baseTime = targetTime.basetime;
let geoJsonUrl = `${JMA_TILE_BASE}/${baseTime}/none/${validTime}/surf/amds_snowd/data.geojson`;
if (TEST_MODE) {
geoJsonUrl = './test_data/snow_data.geojson';
}
currentGeoData = await fetchWithProxy(geoJsonUrl);
// 時刻表示 (GMT -> JST)
const jstDate = targetTime.obstimeJST ? targetTime.obstimeJST : formatUtcToJst(validTime);
document.getElementById('data-time').textContent = jstDate;
} else {
// その他: 新アメダスAPI (JSON) を使用
const latestTime = await getLatestAmedasTime();
// 時刻表示
// YYYY/MM/DD HH:mm 形式
const pad = n => n.toString().padStart(2, '0');
const timeStr = `${latestTime.getFullYear()}/${pad(latestTime.getMonth()+1)}/${pad(latestTime.getDate())} ${pad(latestTime.getHours())}:${pad(latestTime.getMinutes())}`;
document.getElementById('data-time').textContent = timeStr;
// データ取得
const mapData = await fetchAmedasMapData(latestTime);
// GeoJSONへの変換 (amedasStationsとマージ)
const features = [];
Object.keys(mapData).forEach(code => {
const station = amedasStations[code];
const data = mapData[code];
if (station && data) {
const lat = station.lat[0] + station.lat[1] / 60;
const lon = station.lon[0] + station.lon[1] / 60;
const props = {
code: code,
kjName: station.kjName,
knName: station.knName,
// 各データ
temp: data.temp ? data.temp[0] : undefined,
precipitation1h: data.precipitation1h ? data.precipitation1h[0] : undefined,
wind: data.wind ? data.wind[0] : undefined,
windDirection: data.windDirection ? data.windDirection[0] : undefined,
humidity: data.humidity ? data.humidity[0] : undefined,
snow: data.snow ? data.snow[0] : undefined
};
features.push({
type: "Feature",
geometry: {
type: "Point",
coordinates: [lon, lat]
},
properties: props
});
}
});
currentGeoData = {
type: "FeatureCollection",
features: features
};
}
renderMap();
} catch (e) {
console.error(e);
alert("データの取得に失敗しました: " + e.message);
document.getElementById('data-time').textContent = '----/--/-- --:--';
container.innerHTML = '';
}
}
window.onload = loadData;
</script>
</body>
</html>