コード例
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) データと操作用Stateの準備
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>
);
}
コードの読み方
抽象的な地図デザインを ViewState へ設定し、各プロバイダーに対応するネイティブスタイルへ変換させます。
mapDesignOptions は使用中プロバイダーのデザイン一覧から取得し、selectedDesignId は mapViewState.mapDesignType.id を反映するため <select> は制御コンポーネントとして動作します。
handleDesignChange は選択されたオプションを探し、option.design を mapViewState.mapDesignType へ代入します。プロバイダーはそのデザインを地図を作り直さずに対応スタイルへ切り替えます。