MapConductor React SDK Samples

ไอคอนมาร์กเกอร์ | MapLibre | MapConductor React SDK

ตัวอย่าง ไอคอนมาร์กเกอร์ ของ MapConductor React SDK ที่ใช้ MapLibre

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

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

import { useMemo, useState } from 'react';
import {
  ColorDefaultIcon,
  DefaultMarkerIcon,
  createGeoPoint,
  createMapCameraPosition,
  createMarkerState,
  type MarkerState,
} from '@mapconductor/js-sdk-core';
import { InfoBubble, Markers } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import '@mapconductor/react-for-maplibre/style.css';


export default function App() {
  // (1) สร้างแผนที่


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


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


  // (2) เตรียมข้อมูลและสถานะการโต้ตอบ
  const markerData = useMemo(() => [
    { id: 'red', label: 'Red pin', position: { latitude: 35.6812, longitude: 139.7671 },
      icon: new DefaultMarkerIcon({ fillColor: '#ef4444' }) },
    { id: 'blue', label: 'Blue pin', position: { latitude: 35.6862, longitude: 139.7771 },
      icon: new ColorDefaultIcon({ fillColor: '#2563eb', label: 'Tokyo' }) },
  ], []);
  const [selected, setSelected] = useState<MarkerState | null>(null);
  const markers = useMemo(() => markerData.map(item => createMarkerState({
    id: item.id,
    position: createGeoPoint(item.position),
    icon: item.icon,
    extra: item.label,
    onClick: markerState => setSelected(markerState),
  })), [markerData]);


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


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState}>
        <Markers states={markers} />
        {selected && <InfoBubble marker={selected}>{selected.extra as string}</InfoBubble>}
      </MapLibreMapView2D>
    </div>
  );
}

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

ประกอบมาร์กเกอร์จากแหล่งไอคอนหลายแบบ และเปิดบับเบิลเมื่อมีมาร์กเกอร์ถูกเลือก

อาร์เรย์ markers ทำ memo มาจาก markerData และ createMarkerState แต่ละตัวพกไอคอนของตนเองพร้อม onClick ที่บันทึก MarkerState ที่เลือกไว้

<Markers> แบบรวมกลุ่มเรนเดอร์ไอคอนทุกแบบพร้อมกัน และ InfoBubble แสดง selected.extra เฉพาะตอนที่ยังมีมาร์กเกอร์ทำงานอยู่