コード例
import { useMemo, useState } from 'react';
import {
ColorDefaultIcon,
createGeoPoint,
createGeoRectBounds,
createMapCameraPosition,
createMarkerState,
type MarkerState,
} from '@mapconductor/js-sdk-core';
import { InfoBubble } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import { MarkerClusterGroup, type MarkerCluster } from '@mapconductor/react-marker-clustering';
import '@mapconductor/react-for-maplibre/style.css';
export default function App() {
// (1) 地図の作成
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 43.05, longitude: 141.31 }),
zoom: 11,
});
const mapViewState = useMapLibreViewState({
mapDesignType: MapLibreDesign.OsmBrightJa,
cameraPosition: initialCamera,
});
// (2) データと操作用Stateの準備
const postOffices = useMemo(() => [
{ id: 'maruyama', lat: 43.043751, lng: 141.305428, name: '円山西町簡易郵便局' },
{ id: 'jingu', lat: 43.057305, lng: 141.311483, name: '北海道神宮前郵便局' },
{ id: 'miyanomori', lat: 43.057305, lng: 141.303150, name: '札幌宮の森郵便局' },
{ id: 'araiyama', lat: 43.050833, lng: 141.298262, name: '札幌荒井山簡易郵便局' },
{ id: 'futagoyama', lat: 43.043085, lng: 141.318733, name: '札幌双子山郵便局' },
], []);
const [selected, setSelected] = useState<MarkerState | null>(null);
const postOfficeMarkers = useMemo(() => postOffices.map(office => createMarkerState({
id: office.id,
position: createGeoPoint({ latitude: office.lat, longitude: office.lng }),
extra: office.name,
onClick: markerState => setSelected(markerState),
})), [postOffices]);
const clusterIconProvider = (count: number) => new ColorDefaultIcon({
fillColor: '#dc2626', label: String(count), labelTextColor: '#ffffff',
});
const zoomToCluster = (cluster: MarkerCluster) => {
const bounds = createGeoRectBounds();
postOfficeMarkers.filter(marker => cluster.markerIds.includes(marker.id))
.forEach(marker => bounds.extend(marker.position));
mapViewState.fitBounds(bounds, 60);
};
// (3) 地図とオーバーレイの描画
return (
<div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
<MapLibreMapView2D state={mapViewState} onMapClick={() => setSelected(null)}>
<MarkerClusterGroup
markers={postOfficeMarkers}
clusterIconProvider={clusterIconProvider}
onClusterClick={zoomToCluster}
minClusterSize={3}
clusterRadiusPx={80}
/>
{selected && <InfoBubble marker={selected}>{selected.extra as string}</InfoBubble>}
</MapLibreMapView2D>
</div>
);
}
コードの読み方
大量のマーカーをクラスタリングし、拡張 API を通じてクラスタアイコンとクリック動作を指定します。
同じ postOfficeMarkers 配列を <Markers> ではなく MarkerClusterGroup へ渡すことで、地図を引くと近接する局が自動的にまとめられます。
clusterIconProvider がクラスタのバッジを描画し、onClusterClick は zoomToCluster でグループを展開します。minClusterSize と clusterRadiusPx で結合の強さを調整します。