คู่มือการเชื่อมต่อ
เพิ่มแผนที่ MapScale ใน Next.js
ขั้นตอนเริ่มต้นสำหรับแสดงแผนที่ MapLibre ในหน้า Next.js App Router
เริ่มต้น
ติดตั้ง MapLibre GL
MapScale ส่ง style และ tile ที่ใช้กับ MapLibre ได้ ให้ติดตั้งตัว render แผนที่บน browser ก่อน
npm install maplibre-glสร้าง environment variable แบบ public
ใช้ publishable key สำหรับ browser หรือ mobile เท่านั้น อย่าใส่ secret key ใน client app ใน Next.js ตัวแปรที่ browser อ่านได้ต้องขึ้นต้นด้วย NEXT_PUBLIC_
NEXT_PUBLIC_MAPSCALE_KEY=pk_test_your_key_hereสร้าง client map component
แผนที่ต้องแตะ DOM ของ browser จึงต้องเป็น client component ตัวอย่างนี้เริ่มที่กรุงเทพฯ
"use client"
import "maplibre-gl/dist/maplibre-gl.css"
import maplibregl from "maplibre-gl"
import { useEffect, useRef } from "react"
export function MapScaleMap() {
const container = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!container.current) return
const key = process.env.NEXT_PUBLIC_MAPSCALE_KEY
const map = new maplibregl.Map({
container: container.current,
style: `https://api.mapscale.io/styles/v1/streets?key=${key}`,
center: [100.5018, 13.7563],
zoom: 11,
})
map.addControl(new maplibregl.NavigationControl(), "top-right")
return () => map.remove()
}, [])
return <div style={{ width: "100%", height: 480 }} ref={container} />
}นำ component ไปใช้ในหน้า
Import client component เข้าไปใน App Router page ได้เลย ตัว page เองยังเป็น server component ได้
import { MapScaleMap } from "@/components/mapscale-map"
export default function Page() {
return <MapScaleMap />
}