コード例
import { useMemo, useState } from 'react';
import {
createGeoPoint,
createMapCameraPosition,
createMarkerState,
createPolygonState,
type GeoPoint,
} from '@mapconductor/js-sdk-core';
import { Markers, Polygon } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
// (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 [vertices, setVertices] = useState<GeoPoint[]>(initialVertices);
const polygonState = useMemo(() => createPolygonState({
id: 'area',
points: vertices,
fillColor: 'rgba(37, 99, 235, 0.3)',
strokeColor: '#2563eb',
}), [vertices]);
const vertexMarkers = vertices.map((position, index) => createMarkerState({
id: `vertex-${index}`, position, draggable: true,
}));
// (3) 地図とオーバーレイの描画
<MapLibreMapView2D state={mapViewState}>
<Polygon state={polygonState} />
<Markers states={vertexMarkers} />
</MapLibreMapView2D>
コードの読み方
塗りつぶしたポリゴンを描画し、各頂点をマーカーとして見える形で操作可能にします。
vertices は React の state で、頂点が動くたびに useMemo が半透明の青い塗りと実線の枠を持つ PolygonState を作り直します。
各頂点はドラッグ可能なマーカーとして描かれるため、ポリゴンの輪郭を頂点ごとに編集できます。