MapConductor React SDK Samples

円 | MapLibre | MapConductor React SDK

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

このインタラクティブサンプルでは、MapConductorの抽象APIを通じてMapLibre上で円を実装します。

コード例

import { useMemo, useState } from 'react';
import {
  Spherical,
  createCircleState,
  createGeoPoint,
  createMapCameraPosition,
  type MarkerState,
} from '@mapconductor/js-sdk-core';
import { Circle, Marker, Polyline } 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: 21.382314, longitude: -157.933097 }),
    zoom: 13,
  });


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


  // (2) データと操作用Stateの準備
  const center = useMemo(() => createGeoPoint({ latitude: 21.382314, longitude: -157.933097 }), []);
  const [edge, setEdge] = useState(() => Spherical.computeOffset({
    origin: center, distance: 1000, heading: 90,
  }));
  const radiusMeters = useMemo(
    () => Spherical.computeDistanceBetween(center, edge),
    [edge],
  );
  const circleState = useMemo(() => createCircleState({
    id: 'circle', center, radiusMeters,
    fillColor: 'rgba(37, 99, 235, 0.3)',
  }), [radiusMeters]);
  const resizeCircle = (markerState: MarkerState) => setEdge(markerState.position);


  // (3) 地図とオーバーレイの描画


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState}>
        <Circle state={circleState} />
        <Polyline points={[center, edge]} zIndex={1} />
        <Marker position={center} />
        <Marker position={edge} draggable onDrag={resizeCircle} />
      </MapLibreMapView2D>
    </div>
  );
}

コードの読み方

円を描画し、外周のマーカーをドラッグして半径を変更します。半径線は円より上に描画されます。

edge は Spherical.computeOffset で初期化した React の state で、Spherical.computeDistanceBetween(center, edge) から radiusMeters を求め、半径が変わるたびに useMemo が CircleState を作り直します。

外周マーカーのドラッグが resizeCircle を呼んで edge を更新し、zIndex 1 で描いた Polyline が半径線を塗りの上に保ちつつ、円がその半径に合わせて拡大します。