Codebeispiel
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) Die Karte erzeugen
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
zoom: 12,
});
// (2) Daten und Interaktionszustand vorbereiten
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) Die Karte und ihre Overlays rendern
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>
);
}
Wie der Code funktioniert
Position und Zoom zwischen MapLibre und Leaflet synchronisieren.
activeMap merkt sich die Karte mit der Zeigereingabe. Nur diese Karte leitet Änderungen mit moveCameraTo weiter; Ereignisse der anderen Karte werden ignoriert.