2025-03-11-國家資訊與地圖應用程式 -第一步
國家資訊與地圖應用程式
以下是完整、可直接運作的 CountryInfo.vue
,使用 CDN 引入 Vue 和 Leaflet,並適合你目前的開發方式(無 npm、只用 CDN 的方式)。
✅ 完整的 CountryInfo.vue
(配合 CDN)
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
| <!-- CountryInfo.vue --> <template> <div> <h2>🌍 國家資訊與地圖應用程式</h2> <div id="map"></div> </div> </template>
<script setup> import { onMounted } from 'vue'
// CDN Leaflet 是全域變數 L(不需要 import 'leaflet')
onMounted(async () => { const map = L.map('map').setView([20, 0], 2)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map)
// 修正 Leaflet marker 圖示無法顯示(CDN 圖檔) const iconUrl = 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png' const shadowUrl = 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png' const DefaultIcon = L.icon({ iconUrl, shadowUrl, iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] }) L.Marker.prototype.options.icon = DefaultIcon
// 抓取國家資料 const res = await fetch('https://restcountries.com/v3.1/all') const countries = await res.json()
countries.forEach((country) => { const latlng = country.latlng const name = country.name?.common || '未知' const capital = country.capital?.[0] || '未知' const flag = country.flags?.png || '' const currency = country.currencies ? Object.values(country.currencies)[0]?.symbol || '未知' : '未知'
if (latlng?.length === 2) { const marker = L.marker(latlng).addTo(map) marker.bindPopup(` <div style="text-align: center;"> <img src="${flag}" width="80"><br> <strong>${name}</strong><br> 首都:${capital}<br> 貨幣:${currency} </div> `) } }) }) </script>
<style scoped> #map { height: 90vh; width: 100%; } </style>
|
✅ index.html(配合這個 .vue
檔案時)
如果你是用 Vite + CDN,就要確保你的 index.html
(或 public/index.html
)中包含以下內容:
1 2 3 4 5 6 7 8
| <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
這樣 Leaflet 的 CSS 和 JS 就會正確載入。
✅ 如何在 App.vue 使用它
1 2 3 4 5 6 7
| <template> <CountryInfo /> </template>
<script setup> import CountryInfo from './components/CountryInfo.vue' </script>
|
如果你使用的是 Vite 建立的 Vue 專案,但想不用 npm 安裝 leaflet,只靠 CDN,也完全沒問題,只要記得:
- Leaflet 的 JS 不要
import
,直接用 CDN + window.L
- Leaflet 的 CSS 必須放在
index.html
中
當然可以,以下是加入詳細備註說明的版本:
1 2 3 4 5
| <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
|
1 2
| <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
🔎 為什麼這樣放?
資源類型 |
建議放在哪裡 |
原因 |
CSS 樣式 |
<head> 中 |
提早載入樣式,避免地圖變形或閃爍 |
JS 腳本 |
<body> 最後 |
避免阻塞 HTML 載入、避免找不到 DOM 元素錯誤 |