ตัวอย่างโค้ด
import { useMemo } from 'react';
import { createGeoPoint, createMapCameraPosition, createPolygonState } from '@mapconductor/js-sdk-core';
import { Polygon } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import '@mapconductor/react-for-maplibre/style.css';
export default function App() {
// (1) สร้างแผนที่
const initialCamera = createMapCameraPosition({
position: createGeoPoint({ latitude: 40, longitude: -160 }),
zoom: 2,
});
const mapViewState = useMapLibreViewState({
mapDesignType: MapLibreDesign.OsmBrightJa,
cameraPosition: initialCamera,
});
// (2) เตรียมข้อมูลและสถานะการโต้ตอบ
const longDistancePoints = useMemo(() => [
createGeoPoint({ latitude: 35.68, longitude: 139.77 }),
createGeoPoint({ latitude: 37.77, longitude: -122.42 }),
createGeoPoint({ latitude: 21.31, longitude: -157.86 }),
], []);
const geodesicPolygon = useMemo(() => createPolygonState({
id: 'geodesic', points: longDistancePoints, geodesic: true,
}), [longDistancePoints]);
const straightPolygon = useMemo(() => geodesicPolygon.copy({
id: 'straight', geodesic: false, strokeColor: '#2563eb', fillColor: 'rgba(37, 99, 235, 0.15)',
}), [geodesicPolygon]);
const polygons = [geodesicPolygon, straightPolygon];
// (3) เรนเดอร์แผนที่และโอเวอร์เลย์
return (
<div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
<MapLibreMapView state={mapViewState}>
{polygons.map(polygon => (
<Polygon key={polygon.id} state={polygon} />
))}
</MapLibreMapView>
</div>
);
}
โค้ดนี้ทำงานอย่างไร
เปรียบเทียบขอบโพลีกอนแบบจีโอเดสิกกับแบบไม่จีโอเดสิกในระยะไกลและข้ามเส้นแบ่งวันสากล
geodesicPolygon สร้างด้วย geodesic:true ส่วน straightPolygon เป็น .copy ของมันที่ตั้ง geodesic:false บนชุด longDistancePoints เดียวกัน
การเรนเดอร์ทั้งสองพร้อมกันทำให้เห็นว่าขอบแบบจีโอเดสิกโค้งตามเส้นทางที่สั้นที่สุด ขณะที่ขอบตรงยังคงราบไปตามการฉายของแผนที่