MapConductor React SDK Samples

範囲にフィット | MapLibre | MapConductor React SDK

MapConductor React SDKでMapLibreを使用する範囲にフィットのサンプルです。

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

コード例

import { useMemo } from 'react';
import {
  createGeoPoint,
  createGeoRectBounds,
  createMapCameraPosition,
  createMarkerState,
} from '@mapconductor/js-sdk-core';
import { Marker } 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 bounds = useMemo(() => createGeoRectBounds({
    southWest: createGeoPoint({ latitude: 35.66, longitude: 139.74 }),
    northEast: createGeoPoint({ latitude: 35.70, longitude: 139.80 }),
  }), []);
  const marker = useMemo(() => createMarkerState({
    position: createGeoPoint({ latitude: 35.68, longitude: 139.76 }),
    draggable: true,
    onDragStart: state => {
      bounds.southWest = state.position;
      bounds.northEast = state.position;
    },
    onDragEnd: state => {
      bounds.extend(state.position);
      mapViewState.fitBounds(bounds, 40);
    },
  }), [bounds, mapViewState]);


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


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <button onClick={() => mapViewState.fitBounds(bounds, 40)}>Fit bounds</button>
      <MapLibreMapView2D state={mapViewState}>
        <Marker state={marker} />
      </MapLibreMapView2D>
    </div>
  );
}

コードの読み方

fitBounds は指定した矩形が収まるようにカメラを調整します。第2引数は余白のピクセル数です。マーカーをドラッグすると、開始位置と終了位置を含む範囲へ移動します。