MapConductor React SDK Samples

การซิงก์กล้อง | Multiple Providers | MapConductor React SDK

ตัวอย่าง การซิงก์กล้อง ของ MapConductor React SDK ที่ใช้ Multiple Providers

ตัวอย่างเชิงโต้ตอบนี้แสดง การซิงก์กล้อง ผ่านการห่อหุ้มของ MapConductor บน Multiple Providers

ตัวอย่างโค้ด

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) เตรียมข้อมูลและสถานะการโต้ตอบ
  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 บันทึกแผนที่ที่รับการควบคุมจากตัวชี้ เฉพาะแผนที่นั้นจะส่งการเปลี่ยนแปลงด้วย moveCameraTo และละเว้นเหตุการณ์จากอีกแผนที่