MapConductor React SDK Samples

เลเยอร์ราสเตอร์ | MapLibre | MapConductor React SDK

ตัวอย่าง เลเยอร์ราสเตอร์ ของ MapConductor React SDK ที่ใช้ MapLibre

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

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

import { useEffect, useMemo, useState } from 'react';
import {
  RasterLayerSource,
  createGeoPoint,
  createMapCameraPosition,
  createRasterLayerState,
} from '@mapconductor/js-sdk-core';
import { RasterLayer } 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 [opacity, setOpacity] = useState(0.75);
  const tileSource = useMemo(() => RasterLayerSource.UrlTemplate({
    template: 'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png',
    tileSize: 256,
  }), []);
  const layer = useMemo(() => createRasterLayerState({
    source: tileSource,
    opacity: 0.75,
  }), [tileSource]);
  useEffect(() => { layer.opacity = opacity; }, [layer, opacity]);


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


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <input aria-label="Opacity" type="range" min="0" max="1" step="0.05"
        value={opacity} onChange={event => setOpacity(Number(event.target.value))} />
      <MapLibreMapView2D state={mapViewState}>
        <RasterLayer state={layer} />
      </MapLibreMapView2D>
    </div>
  );
}

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

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

tileSource คือ RasterLayerSource.UrlTemplate ที่ชี้ไปยัง URL ของไทล์แบบ {z}/{x}/{y} ส่วนความทึบเก็บอยู่ในสถานะของ React

createRasterLayerState ห่อค่าทั้งสองไว้ และการเปลี่ยนความทึบจะอัปเดต RasterLayer ตัวเดิมในที่ แทนที่จะสร้างแผนที่ใหม่