ตัวอย่างโค้ด
import { useState } from 'react';
import { createGeoPoint, createMapCameraPosition } from '@mapconductor/js-sdk-core';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import '@mapconductor/react-for-maplibre/style.css';
export default function App() {
// (1) สร้างแผนที่
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
zoom: 12,
});
const mapViewState = useMapLibreViewState({
mapDesignType: MapLibreDesign.OsmBrightJa,
cameraPosition: initialCamera,
});
// (2) เตรียมข้อมูลและสถานะการโต้ตอบ
const mapDesignOptions = Object.entries(MapLibreDesign)
.filter((entry): entry is [string, typeof mapViewState.mapDesignType] =>
typeof entry[1] === 'object' && entry[1] !== null && 'id' in entry[1])
.map(([label, design]) => ({ label, design }));
const [selectedDesignId, setSelectedDesignId] = useState(
String(mapViewState.mapDesignType.id),
);
const handleDesignChange = (designId: string) => {
const option = mapDesignOptions.find(item => String(item.design.id) === designId);
if (!option) return;
mapViewState.mapDesignType = option.design;
setSelectedDesignId(String(option.design.id));
};
// (3) เรนเดอร์แผนที่และโอเวอร์เลย์
return (
<div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
<select
value={selectedDesignId}
onChange={event => handleDesignChange(event.target.value)}
>
{mapDesignOptions.map(option => (
<option key={String(option.design.id)} value={String(option.design.id)}>
{option.label}
</option>
))}
</select>
<MapLibreMapView2D state={mapViewState} />
</div>
);
}
โค้ดนี้ทำงานอย่างไร
เปลี่ยนดีไซน์แผนที่เชิงนามธรรมบนสถานะมุมมอง แล้วให้ผู้ให้บริการแต่ละรายแปลงเป็นสไตล์เนทีฟของตน
mapDesignOptions มาจากรายการดีไซน์ของผู้ให้บริการที่ใช้อยู่ และ selectedDesignId สะท้อน mapViewState.mapDesignType.id เพื่อให้ <select> ยังเป็นคอมโพเนนต์แบบควบคุม
handleDesignChange หาตัวเลือกที่เลือกแล้วกำหนด option.design ให้ mapViewState.mapDesignType จากนั้นผู้ให้บริการจะสลับไปใช้สไตล์เนทีฟที่ตรงกันโดยไม่ต้องสร้างแผนที่ใหม่