Ejemplo de código
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) Crear el mapa
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
zoom: 12,
});
// (2) Preparar los datos y el estado de interacción
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) Renderizar el mapa y sus capas
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>
);
}
Cómo funciona el código
Sincroniza la posición y el zoom entre MapLibre y Leaflet.
activeMap registra el mapa que recibe la entrada del puntero. Solo ese mapa envía cambios mediante moveCameraTo; se ignoran los eventos del otro mapa.