ตัวอย่างโค้ด
import { useState } from 'react';
import { createGeoPoint, createMapCameraPosition } from '@mapconductor/js-sdk-core';
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 [palette, setPalette] = useState({
water: '#3a7ca5',
land: '#f2efe6',
street: '#ffffff',
building: '#d9d0c9',
});
// A rule reaches layers by role, so the same words work in someone
// else's style. mix blends each layer's own colour toward the picked
// one; visible: false leaves the layers out of the document, so they
// are not drawn at all.
const rules = buildStyleRules((r) => {
r.role(LayerRole.water, { colorFilter: { mix: { color: palette.water, amount: strength } } });
r.role(LayerRole.building, { visible: false });
});
// (3) เรนเดอร์แผนที่และโอเวอร์เลย์
<MapLibreMapView2D state={mapViewState}>
<VectorTileLayer style={style} rules={rules} opacity={opacity} />
</MapLibreMapView2D>
โค้ดนี้ทำงานอย่างไร
วาดสไตล์เวกเตอร์ของ MapLibre บนแบ็กเอนด์ใดก็ได้ โดยแรสเตอร์ในเบราว์เซอร์แล้วส่งออกเป็นไทล์ราสเตอร์ธรรมดา
แบ็กเอนด์ไม่เคยเห็นสไตล์เวกเตอร์เลย จึงใช้งานได้กับ Google Maps, MapKit, Cesium และตัวอื่นที่อ่านสไตล์เวกเตอร์ไม่ได้
การเปลี่ยนสีจะแทนที่สไตล์และแรสเตอร์เวกเตอร์ไทล์ที่มีอยู่ในหน่วยความจำใหม่ ไม่มีการดาวน์โหลดซ้ำ เพราะเรขาคณิตไม่เปลี่ยน เปลี่ยนแค่สีที่ทาลงไป เลเยอร์สัญลักษณ์จะไม่ถูกวาด เพราะการวางป้ายโดยไม่ชนกันต้องมองเห็นไทล์ข้างเคียง