Mapbox API 教學與應用
1. 什麼是 Mapbox?
Mapbox 是一個提供 地圖服務與空間資料 API 的平台,能夠在網站或 App 中嵌入互動式地圖,並支援 自訂樣式、定位、路線規劃、地理編碼(地址轉座標)、資料視覺化 等功能。
它類似 Google Maps API,但更強調 客製化與前端整合。
2. 基本使用步驟
(1) 註冊並取得 Token
-
前往 Mapbox 官網
-
建立 Access Token(建議限制 URL 或 Domain)
-
在專案中設定環境變數,例如:
VITE_MAPBOX_TOKEN=your_mapbox_access_token
(2) 安裝 SDK
在前端 React / Vite 專案中:
npm install mapbox-gl
(3) 初始化地圖
在 React 中建立一個地圖元件:
import { useEffect, useRef } from "react";
import mapboxgl from "mapbox-gl";
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_TOKEN;
export default function Map() {
const mapContainer = useRef(null);
const map = useRef(null);
useEffect(() => {
if (map.current) return; // 避免重複初始化
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11", // 地圖樣式
center: [121.5654, 25.0330], // 台北座標
zoom: 12
});
// 加入縮放工具
map.current.addControl(new mapboxgl.NavigationControl());
}, []);
return <div ref={mapContainer} style={{ width: "100%", height: "500px" }} />;
}
3. 常見應用案例
(1) 加入標記 (Marker)
new mapboxgl.Marker()
.setLngLat([121.5654, 25.0330]) // 台北 101
.setPopup(new mapboxgl.Popup().setText("台北 101"))
.addTo(map.current);
(2) 更換地圖樣式
Mapbox 提供多種預設樣式:
-
mapbox://styles/mapbox/streets-v11 -
mapbox://styles/mapbox/outdoors-v11 -
mapbox://styles/mapbox/satellite-v9
也可以在 Mapbox Studio 自製地圖樣式。
(3) 路線規劃 (Directions API)
安裝 SDK:
npm install @mapbox/mapbox-gl-directions
使用:
import MapboxDirections from "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions";
map.current.addControl(
new MapboxDirections({
accessToken: mapboxgl.accessToken
}),
"top-left"
);
👉 就能輸入起點/終點,顯示路線。
(4) 地理編碼 (地址 ↔ 座標)
使用 Mapbox Geocoding API
範例:將地址轉換成座標
fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/台北101.json?access_token=${mapboxgl.accessToken}`)
.then(res => res.json())
.then(data => {
console.log(data.features[0].center); // [121.5645, 25.0339]
});
(5) 地理資料視覺化
可以透過 GeoJSON 在地圖上繪製資料:
map.current.on("load", () => {
map.current.addSource("points", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: { type: "Point", coordinates: [121.5654, 25.0330] },
properties: { title: "台北 101" }
}
]
}
});
map.current.addLayer({
id: "points-layer",
type: "circle",
source: "points",
paint: {
"circle-radius": 8,
"circle-color": "#FF5733"
}
});
});
4. 應用場景舉例
-
計程車/外送平台 → 即時定位 + 路線導航
-
不動產網站 → 地圖篩選房屋、視覺化社區數據
-
旅遊網站 → 標記景點、客製化地圖風格
-
數據儀表板 → 將地理數據 (人口、銷售、流量) 視覺化