ตัวอย่างโค้ด
import { useMemo, useState } from 'react';
import { createGeoPoint, createMapCameraPosition, createMarkerState } from '@mapconductor/js-sdk-core';
import { InfoBubble, Marker } 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) เตรียมข้อมูลและสถานะการโต้ตอบ
const position = createGeoPoint({ latitude: 35.6812, longitude: 139.7671 });
const [selected, setSelected] = useState(false);
const marker = useMemo(() => createMarkerState({
id: 'place', position, onClick: () => setSelected(true),
}), [position]);
// (3) เรนเดอร์แผนที่และโอเวอร์เลย์
<MapLibreMapView2D state={mapViewState}>
<Marker state={marker} />
{selected && (
<InfoBubble marker={marker}>Simple text content</InfoBubble>
)}
</MapLibreMapView2D>
โค้ดนี้ทำงานอย่างไร
ตรึงบับเบิลเนื้อหา React อย่างง่ายไว้กับมาร์กเกอร์ที่ผู้ใช้เลือก
ค่าบูลีน selected เก็บอยู่ใน useState และ onClick ของมาร์กเกอร์เปลี่ยนค่าเป็น true
InfoBubble เรนเดอร์เฉพาะตอนที่ selected เป็น true และมีแค่ข้อความล้วน ซึ่งเป็นรูปแบบพื้นฐานที่สุดของบับเบิลที่ตรึงกับมาร์กเกอร์