HRES WebGL 图层接入
使用 leaflet-wind WebglLayer 对 HRES 区域温度数据进行 GPU 着色渲染,并支持前端直接点击取值,无需额外接口请求。
WebGL 渲染方式相比图片叠加具有更高性能和更丰富的交互能力。leaflet-wind 的 WebglLayer 在接收到编码图(JPEG + Exif)后,由 GPU Shader 完成数据解码和颜色映射,支持前端直接点击取值,不需要为取值额外发起网络请求。
本文以 HRES 温度图层为例,演示如何在 React 和 Vue 项目中接入 WebGL 图层。
1. 关键参数说明
| 参数 | 说明 |
|---|---|
| 编码图 URL | https://api.mirror-earth.com/api/vis/hres/temperature_2m/{time}.jpeg?size=2048&apikey={apikey} |
ImageSource.coordinates | 四角坐标,按 NW → NE → SE → SW 顺序,格式为 [lon, lat]:[[69.96, 55.04], [140.08, 55.04], [140.08, 14.96], [69.96, 14.96]] |
decodeType | DecodeType.imageWithExif:从图片 Exif 中读取数值区间并解码 |
renderFrom | RenderFrom.r:数值编码在 R 通道 |
renderType | RenderType.colorize:按色板着色 |
displayRange | [-50, 50]:可视数值范围(℃) |
wrapX | false(HRES 为区域模型,不需要经度循环) |
picking | true:开启前端取值支持 |
| 取值方式 | await layer.picker(latlng) → 返回 [value] |
编码图路径说明:HRES 的 WebGL 编码图路径为 /api/vis/hres/{element}/{time}.jpeg(无 /part/ 前缀,无 tms=4326),与图片接入的 /part/ 路径不同。
2. 安装依赖
npm install leaflet leaflet-wind
3. 示例代码
import { useEffect, useRef, useState } from 'react';
import 'leaflet/dist/leaflet.css';
const API_KEY = 'YOUR_API_KEY';
// HRES 四角坐标:[NW, NE, SE, SW],格式为 [lon, lat]
const HRES_COORDS: [number, number][] = [
[69.9588, 55.0412], // NW
[140.0799, 55.0412], // NE
[140.0799, 14.9587], // SE
[69.9588, 14.9587], // SW
];
// 温度色板:值 → RGBA
const TEMP_COLORS: [number, number[]][] = [
[-30, [98, 113, 183, 255]],
[-20, [57, 97, 159, 255]],
[-10, [74, 148, 169, 255]],
[0, [77, 141, 123, 255]],
[10, [83, 165, 83, 255]],
[20, [167, 157, 81, 255]],
[30, [159, 127, 58, 255]],
[40, [175, 80, 136, 255]],
];
export default function HresWebglDemo() {
const mapRef = useRef<HTMLDivElement>(null);
const mapInstance = useRef<any>(null);
const layerRef = useRef<any>(null);
const [clickedValue, setClickedValue] = useState<string | null>(null);
const [status, setStatus] = useState('正在加载...');
useEffect(() => {
if (!mapRef.current) return;
let isMounted = true;
const init = async () => {
const L: any = await import('leaflet');
const { WebglLayer, ImageSource, DecodeType, RenderFrom, RenderType } =
await import('leaflet-wind');
if (!isMounted || !mapRef.current) return;
const map = new L.Map(mapRef.current, { zoom: 4, center: [35.0, 105.0] });
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
subdomains: ['a', 'b', 'c', 'd'],
attribution: '© CartoDB',
}).addTo(map);
mapInstance.current = map;
try {
// 1. 获取最新时间
const metaRes = await fetch(
`https://api.mirror-earth.com/api/vis/hres/meta?apikey=${API_KEY}&timezone=Asia/Shanghai`
);
const { data: [time] } = await metaRes.json();
// 2. 构建编码图 URL(注意:无 /part/ 前缀,无 tms=4326)
const url = `https://api.mirror-earth.com/api/vis/hres/temperature_2m/${time}.jpeg?size=2048&apikey=${API_KEY}`;
// 3. 初始化数据源
const source = new ImageSource('temperature', {
url,
coordinates: HRES_COORDS,
decodeType: DecodeType.imageWithExif,
wrapX: false, // HRES 为区域模型
});
// 4. 构建插值色板
const interpolateColor = TEMP_COLORS.reduce(
(acc, [val, rgba]) => acc.concat(val, `rgba(${rgba.join(',')})`),
[] as any[]
);
// 5. 创建 WebGL 图层
const layer = new WebglLayer('temperature', source, {
styleSpec: {
'fill-color': ['interpolate', ['linear'], ['get', 'value'], ...interpolateColor],
opacity: 0.8,
},
renderFrom: RenderFrom.r,
displayRange: [-50, 50],
renderType: RenderType.colorize,
picking: true, // 开启前端取值
});
map.addLayer(layer);
layerRef.current = layer;
if (isMounted) setStatus('HRES WebGL 图层已加载,点击地图取值');
// 6. 点击取值(直接从 GPU 缓冲区读取,无需网络请求)
map.on('click', async (e: any) => {
if (!layerRef.current) return;
const [v] = await layerRef.current.picker(e.latlng);
setClickedValue(
v != null
? `坐标: ${e.latlng.lat.toFixed(2)}, ${e.latlng.lng.toFixed(2)} | 温度: ${v.toFixed(2)}℃`
: '无数据(超出图层范围)'
);
});
} catch {
if (isMounted) setStatus('图层加载失败,请检查 API Key');
}
};
init();
return () => {
isMounted = false;
mapInstance.current?.remove();
mapInstance.current = null;
};
}, []);
return (
<div>
<p style={{ padding: '8px 12px', background: '#fafafa', margin: 0 }}>{status}</p>
<div ref={mapRef} style={{ width: '100%', height: '500px' }} />
{clickedValue && (
<div style={{ padding: '8px 12px', background: '#f6ffed', borderTop: '1px solid #b7eb8f' }}>
{clickedValue}
</div>
)}
</div>
);
}<template>
<div>
<p style="padding: 8px 12px; background: #fafafa; margin: 0">{{ status }}</p>
<div ref="mapRef" style="width: 100%; height: 500px" />
<div v-if="clickedValue" style="padding: 8px 12px; background: #f6ffed; border-top: 1px solid #b7eb8f">
{{ clickedValue }}
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, shallowRef } from 'vue';
const API_KEY = 'YOUR_API_KEY';
// HRES 四角坐标:[NW, NE, SE, SW],格式为 [lon, lat]
const HRES_COORDS: [number, number][] = [
[69.9588, 55.0412], // NW
[140.0799, 55.0412], // NE
[140.0799, 14.9587], // SE
[69.9588, 14.9587], // SW
];
// 温度色板:值 → RGBA
const TEMP_COLORS: [number, number[]][] = [
[-30, [98, 113, 183, 255]],
[-20, [57, 97, 159, 255]],
[-10, [74, 148, 169, 255]],
[0, [77, 141, 123, 255]],
[10, [83, 165, 83, 255]],
[20, [167, 157, 81, 255]],
[30, [159, 127, 58, 255]],
[40, [175, 80, 136, 255]],
];
const mapRef = ref<HTMLDivElement>();
const clickedValue = ref<string | null>(null);
const status = ref('正在加载...');
const mapInstance = shallowRef<any>(null);
const layerInstance = shallowRef<any>(null);
onMounted(async () => {
const L: any = await import('leaflet');
const { WebglLayer, ImageSource, DecodeType, RenderFrom, RenderType } =
await import('leaflet-wind');
await import('leaflet/dist/leaflet.css');
const map = new L.Map(mapRef.value!, { zoom: 4, center: [35.0, 105.0] });
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
subdomains: ['a', 'b', 'c', 'd'],
attribution: '© CartoDB',
}).addTo(map);
mapInstance.value = map;
try {
// 1. 获取最新时间
const metaRes = await fetch(
`https://api.mirror-earth.com/api/vis/hres/meta?apikey=${API_KEY}&timezone=Asia/Shanghai`
);
const { data: [time] } = await metaRes.json();
// 2. 构建编码图 URL(注意:无 /part/ 前缀,无 tms=4326)
const url = `https://api.mirror-earth.com/api/vis/hres/temperature_2m/${time}.jpeg?size=2048&apikey=${API_KEY}`;
// 3. 初始化数据源
const source = new ImageSource('temperature', {
url,
coordinates: HRES_COORDS,
decodeType: DecodeType.imageWithExif,
wrapX: false, // HRES 为区域模型
});
// 4. 构建插值色板
const interpolateColor = TEMP_COLORS.reduce(
(acc, [val, rgba]) => acc.concat(val, `rgba(${rgba.join(',')})`),
[] as any[]
);
// 5. 创建 WebGL 图层
const layer = new WebglLayer('temperature', source, {
styleSpec: {
'fill-color': ['interpolate', ['linear'], ['get', 'value'], ...interpolateColor],
opacity: 0.8,
},
renderFrom: RenderFrom.r,
displayRange: [-50, 50],
renderType: RenderType.colorize,
picking: true,
});
map.addLayer(layer);
layerInstance.value = layer;
status.value = 'HRES WebGL 图层已加载,点击地图取值';
// 6. 前端直接取值
map.on('click', async (e: any) => {
if (!layerInstance.value) return;
const [v] = await layerInstance.value.picker(e.latlng);
clickedValue.value = v != null
? `坐标: ${e.latlng.lat.toFixed(2)}, ${e.latlng.lng.toFixed(2)} | 温度: ${v.toFixed(2)}℃`
: '无数据(超出图层范围)';
});
} catch {
status.value = '图层加载失败,请检查 API Key';
}
});
onUnmounted(() => {
mapInstance.value?.remove();
mapInstance.value = null;
});
</script>4. Demo 仓库
完整可运行示例已上传至 Gitee:
- 仓库:https://gitee.com/gfyml/me-layer-demo.git
- React 示例:
react-demo/src/components/WebglLayerDemo.tsx - Vue 示例:
vue-demo/src/components/WebglLayerDemo.vue