コード例
import { useState } from 'react';
import { createGeoPoint, createMapCameraPosition } from '@mapconductor/js-sdk-core';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
// (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 = providerDesignOptions;
const [selectedDesignId, setSelectedDesignId] = useState(
String(mapViewState.mapDesignType.id),
);
// (3) 地図とオーバーレイの描画
const handleDesignChange = (designId: string) => {
const option = mapDesignOptions.find(item => item.design.id === designId);
if (!option) return;
mapViewState.mapDesignType = option.design;
setSelectedDesignId(String(option.design.id));
};
<MapLibreMapView2D state={mapViewState}>
<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>
コードの読み方
抽象的な地図デザインを ViewState へ設定し、各プロバイダーに対応するネイティブスタイルへ変換させます。
mapDesignOptions は使用中プロバイダーのデザイン一覧から取得し、selectedDesignId は mapViewState.mapDesignType.id を反映するため <select> は制御コンポーネントとして動作します。
handleDesignChange は選択されたオプションを探し、option.design を mapViewState.mapDesignType へ代入します。プロバイダーはそのデザインを地図を作り直さずに対応スタイルへ切り替えます。