MapConductor React SDK Samples

GeoJSON レイヤー | MapLibre | MapConductor React SDK

MapConductor React SDKでMapLibreを使用するGeoJSON レイヤーのサンプルです。

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

コード例

import { useMemo, useState } from 'react';
import { createGeoPoint, createMapCameraPosition, type GeoPoint } from '@mapconductor/js-sdk-core';
import { InfoBubble } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import {
  GeoJSONLayer,
  GeoJSONLayerState,
  GeoJSONParser,
  colorArgb,
} from '@mapconductor/react-geojson';
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 features = useMemo(() => GeoJSONParser.parseFeatures(JSON.stringify({
    type: 'FeatureCollection',
    features: [{ type: 'Feature', properties: { name: 'Sample railway' },
      geometry: { type: 'LineString', coordinates: [[139.75, 35.68], [139.77, 35.69], [139.79, 35.68]] },
    }],
  })), []);
  const [selected, setSelected] = useState<{
    position: GeoPoint; properties: Record<string, unknown>;
  } | null>(null);
  const layerState = useMemo(() => new GeoJSONLayerState({
    strokeColor: colorArgb(200, 250, 36, 29),
    strokeWidth: 6,
    onClick: (feature, position) => setSelected({ position: createGeoPoint(position), properties: feature.properties ?? {} }),
  }), []);
  const handleMapClick = (point: GeoPoint) => {
    if (!layerState.processClick(point, 10, mapViewState.cameraPosition.zoom)) setSelected(null);
  };


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


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState} onMapClick={handleMapClick}>
        <GeoJSONLayer state={layerState} features={features} />
        {selected && (
          <InfoBubble position={selected.position}>
            <pre>{JSON.stringify(selected.properties, null, 2)}</pre>
          </InfoBubble>
        )}
      </MapLibreMapView2D>
    </div>
  );
}

コードの読み方

外部データサーバーなしで試せるよう、説明用の鉄道路線を GeoJSON としてコード内に用意しています。

handleMapClick は現在のズームを渡して processClick を呼びます。ヒット時に layerState.onClick が属性とクリック地点を保存して InfoBubble へ表示し、何もない場所をクリックすると選択を解除します。