MapConductor React SDK Samples

マーカーアイコン | MapLibre | MapConductor React SDK

MapConductor React SDKでMapLibreを使用するマーカーアイコンのサンプルです。

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

コード例

import { useMemo, useState } from 'react';
import {
  ColorDefaultIcon,
  DefaultMarkerIcon,
  createGeoPoint,
  createMapCameraPosition,
  createMarkerState,
  type MarkerState,
} from '@mapconductor/js-sdk-core';
import { InfoBubble, Markers } 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 markerData = useMemo(() => [
    { id: 'red', label: 'Red pin', position: { latitude: 35.6812, longitude: 139.7671 },
      icon: new DefaultMarkerIcon({ fillColor: '#ef4444' }) },
    { id: 'blue', label: 'Blue pin', position: { latitude: 35.6862, longitude: 139.7771 },
      icon: new ColorDefaultIcon({ fillColor: '#2563eb', label: 'Tokyo' }) },
  ], []);
  const [selected, setSelected] = useState<MarkerState | null>(null);
  const markers = useMemo(() => markerData.map(item => createMarkerState({
    id: item.id,
    position: createGeoPoint(item.position),
    icon: item.icon,
    extra: item.label,
    onClick: markerState => setSelected(markerState),
  })), [markerData]);


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


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState}>
        <Markers states={markers} />
        {selected && <InfoBubble marker={selected}>{selected.extra as string}</InfoBubble>}
      </MapLibreMapView2D>
    </div>
  );
}

コードの読み方

複数種類のアイコンを持つマーカーを構成し、選択されたマーカーに吹き出しを表示します。

markers は markerData から useMemo で生成し、各 createMarkerState が独自の icon と、選択された MarkerState を記録する onClick を持ちます。

一括描画の <Markers> が異なるアイコンをまとめて描画し、InfoBubble はマーカーが選択されている間だけ selected.extra を表示します。