コード例
import { useRef } from 'react';
import { createGeoPoint, createMapCameraPosition, type MapCameraPosition } from '@mapconductor/js-sdk-core';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import { LeafletDesign, LeafletMapView, useLeafletMapViewState } from '@mapconductor/react-for-leaflet';
import '@mapconductor/react-for-maplibre/style.css';
import '@mapconductor/react-for-leaflet/style.css';
export default function App() {
// (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,
});
// Only the map being manipulated forwards camera events. Mirrored events cannot echo.
const activeMap = useRef<'left' | 'right' | null>(null);
const syncCamera = (source: 'left' | 'right', camera: MapCameraPosition) => {
if (activeMap.current !== source) return;
const targetState = source === 'left' ? rightMapState : leftMapState;
targetState.moveCameraTo(createMapCameraPosition({ position: camera.position, zoom: camera.zoom }), 0);
};
// (3) 地図とオーバーレイの描画
return (
<div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', height: '100%' }}>
<div onPointerDown={() => { activeMap.current = 'left'; }}
onWheel={() => { activeMap.current = 'left'; }} onFocusCapture={() => { activeMap.current = 'left'; }}>
<MapLibreMapView2D state={leftMapState}
onCameraMove={camera => syncCamera('left', camera)} />
</div>
<div onPointerDown={() => { activeMap.current = 'right'; }}
onWheel={() => { activeMap.current = 'right'; }} onFocusCapture={() => { activeMap.current = 'right'; }}>
<LeafletMapView state={rightMapState}
onCameraMove={camera => syncCamera('right', camera)} />
</div>
</div>
</div>
);
}
コードの読み方
MapLibre と Leaflet の間でカメラ位置とズームを同期します。
ポインター操作を受けた地図を activeMap に記録し、その地図のカメライベントだけを転送します。移動先から返るイベントは転送しないため、相互更新がループしません。