MapConductor React SDK Samples

ดีไซน์แผนที่ | MapLibre | MapConductor React SDK

ตัวอย่าง ดีไซน์แผนที่ ของ MapConductor React SDK ที่ใช้ MapLibre

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

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

import { useState } from 'react';
import { createGeoPoint, createMapCameraPosition } from '@mapconductor/js-sdk-core';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';


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


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


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


// (2) เตรียมข้อมูลและสถานะการโต้ตอบ
const mapDesignOptions = providerDesignOptions;
const [selectedDesignId, setSelectedDesignId] = useState(
  String(mapViewState.mapDesignType.id),
);


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


const handleDesignChange = (designId: string) => {
  const option = mapDesignOptions.find(item => item.design.id === designId);
  if (!option) return;
  mapViewState.mapDesignType = option.design;
  setSelectedDesignId(String(option.design.id));
};


<MapLibreMapView2D state={mapViewState}>
  <select
    value={selectedDesignId}
    onChange={event => handleDesignChange(event.target.value)}
  >
    {mapDesignOptions.map(option => (
      <option key={String(option.design.id)} value={String(option.design.id)}>
        {option.label}
      </option>
    ))}
  </select>
</MapLibreMapView2D>

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

เปลี่ยนดีไซน์แผนที่เชิงนามธรรมบนสถานะมุมมอง แล้วให้ผู้ให้บริการแต่ละรายแปลงเป็นสไตล์เนทีฟของตน

mapDesignOptions มาจากรายการดีไซน์ของผู้ให้บริการที่ใช้อยู่ และ selectedDesignId สะท้อน mapViewState.mapDesignType.id เพื่อให้ <select> ยังเป็นคอมโพเนนต์แบบควบคุม

handleDesignChange หาตัวเลือกที่เลือกแล้วกำหนด option.design ให้ mapViewState.mapDesignType จากนั้นผู้ให้บริการจะสลับไปใช้สไตล์เนทีฟที่ตรงกันโดยไม่ต้องสร้างแผนที่ใหม่