MapConductor React SDK Samples

ポリゴン | MapLibre | MapConductor React SDK

MapConductor React SDKでMapLibreを使用するポリゴンのサンプルです。

このインタラクティブサンプルでは、MapConductorの抽象APIを通じて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) データと操作用Stateの準備
  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 の state で、頂点が動くたびに useMemo が半透明の青い塗りと実線の枠を持つ PolygonState を作り直します。

各頂点はドラッグ可能なマーカーとして描かれるため、ポリゴンの輪郭を頂点ごとに編集できます。