MapConductor React SDK Samples

การจัดกลุ่มที่ทำการไปรษณีย์ | MapLibre | MapConductor React SDK

ตัวอย่าง การจัดกลุ่มที่ทำการไปรษณีย์ ของ MapConductor React SDK ที่ใช้ MapLibre

ตัวอย่างเชิงโต้ตอบนี้แสดง การจัดกลุ่มที่ทำการไปรษณีย์ ผ่านการห่อหุ้มของ MapConductor บน MapLibre

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

import { useMemo, useState } from 'react';
import {
  MarkerTilingOptions,
  createGeoPoint,
  createMapCameraPosition,
  createMarkerState,
  type MarkerState,
} from '@mapconductor/js-sdk-core';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import { MarkerClusterGroup } from '@mapconductor/react-marker-clustering';


// (1) สร้างแผนที่


const initialCamera = createMapCameraPosition({
  position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
  zoom: 12,
});


const mapViewState = useMapLibreViewState({
  mapDesignType: MapLibreDesign.OsmBrightJa,
  cameraPosition: initialCamera,
});


// (2) เตรียมข้อมูลและสถานะการโต้ตอบ
const [selected, setSelected] = useState<MarkerState | null>(null);
const postOfficeMarkers = useMemo(() => postOffices.map(office => createMarkerState({
  id: office.id,
  position: createGeoPoint({ latitude: office.lat, longitude: office.lng }),
  extra: office,
  onClick: markerState => setSelected(markerState),
})), [postOffices]);
const markerTilingOptions = {
  ...MarkerTilingOptions.Default,
  iconScaleCallback: (_state: MarkerState, zoom: number) =>
    zoom > 10 ? 0.8 : zoom > 5 ? 0.5 : 0.2,
};


// (3) เรนเดอร์แผนที่และโอเวอร์เลย์


<MapLibreMapView2D state={mapViewState}>
  <MarkerClusterGroup
    markers={postOfficeMarkers}
    clusterIconProvider={clusterIconProvider}
    onClusterClick={zoomToCluster}
    minClusterSize={3}
    clusterRadiusPx={80}
  />
</MapLibreMapView2D>

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

จัดกลุ่มมาร์กเกอร์จำนวนมาก และกำหนดไอคอนกลุ่มกับพฤติกรรมการคลิกเองผ่าน API ของส่วนขยาย

อาร์เรย์ postOfficeMarkers ชุดเดิมถูกป้อนให้ MarkerClusterGroup แทน <Markers> ที่ทำการที่อยู่ใกล้กันจึงถูกจัดกลุ่มอัตโนมัติเมื่อซูมออก

clusterIconProvider วาดป้ายของกลุ่ม onClusterClick เรียก zoomToCluster เพื่อเปิดกลุ่ม ส่วน minClusterSize กับ clusterRadiusPx ใช้ปรับว่าจะรวมจุดเข้าด้วยกันมากแค่ไหน