MapConductor React SDK Samples

โพลีกอน | MapLibre | MapConductor React SDK

ตัวอย่าง โพลีกอน ของ MapConductor React SDK ที่ใช้ MapLibre

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

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

import { useMemo, useState } from 'react';
import {
  createGeoPoint,
  createMapCameraPosition,
  createMarkerState,
  createPolygonState,
  type GeoPoint,
} from '@mapconductor/js-sdk-core';
import { Markers, Polygon } 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 initialVertices = [
    createGeoPoint({ latitude: 35.69, longitude: 139.75 }),
    createGeoPoint({ latitude: 35.67, longitude: 139.75 }),
    createGeoPoint({ latitude: 35.67, longitude: 139.79 }),
  ];
  const [vertices, setVertices] = useState<GeoPoint[]>(initialVertices);
  const polygonState = useMemo(() => createPolygonState({
    id: 'area',
    points: vertices,
    fillColor: 'rgba(37, 99, 235, 0.3)',
    strokeColor: '#2563eb',
  }), [vertices]);
  const vertexMarkers = useMemo(() => initialVertices.map((position, index) => createMarkerState({
    id: `vertex-${index}`, position, draggable: true,
    onDrag: marker => setVertices(current => current.map((point, i) => i === index ? marker.position : point)),
  })), []);


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


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState}>
        <Polygon state={polygonState} />
        <Markers states={vertexMarkers} />
      </MapLibreMapView2D>
    </div>
  );
}

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

วาดโพลีกอนแบบมีสีเติม และใช้มาร์กเกอร์ทำให้จุดยอดแต่ละจุดมองเห็นและโต้ตอบได้

อาร์เรย์ vertices เป็นสถานะของ React และ useMemo จะสร้าง PolygonState ใหม่ทุกครั้งที่จุดยอดขยับ โดยเป็นสีเติมน้ำเงินโปร่งแสงพร้อมเส้นขอบทึบ

จุดยอดแต่ละจุดวาดเป็นมาร์กเกอร์ที่ลากได้ เส้นขอบของโพลีกอนจึงแก้ไขได้ทีละจุด