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, 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) เตรียมข้อมูลและสถานะการโต้ตอบ
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>

โค้ดนี้ทำงานอย่างไร

ส่งต่อการเปลี่ยนแปลงของกล้องระหว่างผู้ให้บริการสองรายที่เรนเดอร์แยกกัน พร้อมกันไม่ให้เกิดลูปป้อนกลับ

หน้านี้ตั้งใจให้ผู้ให้บริการสองรายทำงานพร้อมกัน โดย useMapLibreViewState และ useLeafletMapViewState ต่างสร้างสถานะมุมมองของตัวเองที่เริ่มจาก initialCamera เดียวกัน

syncCamera คัดลอกกล้องของแผนที่ฝั่งหนึ่งไปยังอีกฝั่งด้วย moveCameraTo(camera, 0) และตัวกันด้วย useRef ที่ปลดใน requestAnimationFrame ถัดไปจะหยุดไม่ให้การอัปเดตที่สะท้อนกลับวนซ้ำ