ตัวอย่างโค้ด
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';
// (1) สร้างแผนที่
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
zoom: 12,
});
const mapViewState = useMapLibreViewState({
mapDesignType: MapLibreDesign.OsmBrightJa,
cameraPosition: initialCamera,
});
// (2) เตรียมข้อมูลและสถานะการโต้ตอบ
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 แล้วแสดงคุณสมบัติของฟีเจอร์ที่เลือกไว้ ณ ตำแหน่งภูมิศาสตร์ที่คลิก
ทั้งฟีเจอร์และฟีเจอร์ที่เลือกอยู่ในสถานะของ React ส่วน layerState คือ GeoJSONLayerState ที่ถือข้อมูลเส้นทางรถไฟ
handleMapClick หาว่าโดนฟีเจอร์ใดแล้วเก็บไว้ จากนั้น InfoBubble จะตรึง PropertyTable ของคุณสมบัตินั้นไว้ที่พิกัดที่คลิก