將資料來源從 spots.json 切換到後端 /scan API

- 於檔頭新增 API_URL / SCAN_CENTER 常數,方便之後切換 IP / port
- fetch 改 POST,body 帶 lat/lng(後端要求的 schema,值本身會被忽略)
- 空 items 改顯示「目前無資料」提示,處理 API stale-while-revalidate
  快取剛過期時首打會回空陣列的情境
- 保留 toList() 對頂層陣列的相容、保留座標欄位三種別名 fallback

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
timmy
2026-04-20 10:01:55 +08:00
parent cbafad2f37
commit 473211c86c

View File

@@ -208,6 +208,11 @@
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
// 後端 API 端點;改 IP / port 只改這一行
const API_URL = 'http://192.168.88.108:8008/scan';
// 掃描中心座標(後端目前會忽略此值,純 schema 相容)
const SCAN_CENTER = { lat: 25.0478, lng: 121.5170 };
const map = L.map('map', { worldCopyJump: true, zoomControl: false }).setView([23.7, 121], 7);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
@@ -388,12 +393,18 @@
box.addTo(map);
}
fetch('spots.json', { cache: 'no-cache' })
fetch(API_URL, {
method: 'POST',
cache: 'no-cache',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ lat: SCAN_CENTER.lat, lng: SCAN_CENTER.lng })
})
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
return res.json();
})
.then(json => {
// 後端回 {source, items: [...]}; toList() 也相容頂層陣列的舊格式
const list = toList(json);
const markers = [];
@@ -449,12 +460,13 @@
const group = L.featureGroup(markers);
map.fitBounds(group.getBounds().pad(0.2));
} else {
showLoadError('沒有可顯示的座標');
// API stale-while-revalidate快取剛過期時會先回空陣列幾十秒後再打才有資料
showLoadError('目前無資料,稍後再試');
}
})
.catch(err => {
console.error('讀取 spots.json 失敗:', err);
showLoadError(`spots.json 載入失敗:${err.message}`);
console.error('讀取掃描資料失敗:', err);
showLoadError(`掃描資料載入失敗:${err.message}`);
});
</script>
</body>