コード例
import { useMemo, useState } from 'react';
import { createGeoPoint, createMapCameraPosition } from '@mapconductor/js-sdk-core';
import { InfoBubble } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import { GeoJSONLayer, GeoJSONLayerState, type GeoJSONFeatureData } from '@mapconductor/react-geojson-layer';
// (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, setFeatures] = useState<GeoJSONFeatureData[]>([]);
const [selected, setSelected] = useState<SelectedFeature | null>(null);
const layerState = useMemo(() => new GeoJSONLayerState({ id: 'railways' }), []);
// (3) 地図とオーバーレイの描画
<MapLibreMapView2D state={mapViewState} onMapClick={handleMapClick}>
<GeoJSONLayer state={layerState} features={features} />
{selected && (
<InfoBubble position={selected.position}>
<PropertyTable properties={selected.properties} />
</InfoBubble>
)}
</MapLibreMapView2D>
コードの読み方
GeoJSON Feature へのクリックを判定し、選択した Feature の属性をクリック地点に表示します。
features と選択中の Feature はどちらも React の state に保持し、layerState は鉄道データ用の GeoJSONLayerState です。
handleMapClick がどの Feature に当たったかを判定して保存し、InfoBubble がその属性の PropertyTable をクリック座標に固定します。