コード例
import { useRef } from 'react';
import { createGeoPoint, createMapCameraPosition, type MapCameraPosition } from '@mapconductor/js-sdk-core';
import { MapLibreDesign, MapLibreMapView, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import { LeafletDesign, LeafletMapView, useLeafletMapViewState } from '@mapconductor/react-for-leaflet';
// (1) 地図の作成
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
zoom: 12,
});
// (2) データと操作用Stateの準備
const leftMapState = useMapLibreViewState({
mapDesignType: MapLibreDesign.OsmBrightJa,
cameraPosition: initialCamera,
});
const rightMapState = useLeafletMapViewState({
mapDesignType: LeafletDesign.OpenStreetMap,
cameraPosition: initialCamera,
});
const leftProgrammatic = useRef(false);
const rightProgrammatic = useRef(false);
// (3) 地図とオーバーレイの描画
const syncCamera = (
source: 'left' | 'right',
camera: MapCameraPosition,
) => {
const targetState = source === 'left' ? rightMapState : leftMapState;
const targetGuard = source === 'left' ? rightProgrammatic : leftProgrammatic;
if (targetGuard.current) return;
targetGuard.current = true;
targetState.moveCameraTo(camera, 0);
requestAnimationFrame(() => { targetGuard.current = false; });
};
<div className="camera-grid">
<MapLibreMapView
state={leftMapState}
onCameraMove={camera => syncCamera('left', camera)}
/>
<LeafletMapView
state={rightMapState}
onCameraMove={camera => syncCamera('right', camera)}
/>
</div>
コードの読み方
独立して描画した2つのプロバイダー間でカメラ変更を転送し、相互更新のループを抑制します。
このページだけは2種類のプロバイダーを同時に使います。useMapLibreViewState と useLeafletMapViewState が同じ initialCamera から別々の ViewState を作ります。
syncCamera は一方のカメラを moveCameraTo(camera, 0) でもう一方へ転写し、useRef のガードを次の requestAnimationFrame で解除することで、転写した更新が跳ね返るのを防ぎます。