Skip to Content

镜像地球开放平台

GFS 全球预报 WebGL 图层接入

使用 leaflet-wind WebglLayer 对 GFS 全球预报温度数据进行 WebGL 渲染,覆盖全球范围,支持经度循环展示与前端点击取值。

GFS(Global Forecast System)是美国国家海洋和大气管理局(NOAA)发布的全球数值天气预报模型,分辨率约 25km,覆盖全球(-180° ~ 180° 经度,-85.05° ~ 85.05° 纬度)。

相比 HRES 区域模型,全球模型有两个关键差异:

  1. 数据范围覆盖全球,sourceCoords 需要覆盖完整的全球边界
  2. 经度可循环,需要设置 wrapX: true,使地图横向拖拽时图层能正确平铺

1. 关键参数说明

参数说明
modelarchive_gfs
编码图 URLhttps://api.mirror-earth.com/api/vis/archive_gfs/temperature_2m/{time}.jpeg?size=2048&apikey={apikey}
coordinates全球四角坐标:[[-180, 85.05], [180, 85.05], [180, -85.05], [-180, -85.05]](NW→NE→SE→SW,格式 [lon, lat]
wrapXtrue(全球模型需要经度循环)
displayRange[-50, 50](℃)
pickingtrue,通过 layer.picker(latlng) 前端取值
地图初始视角center: [20.0, 0.0]zoom: 2

GFS vs HRES 接入差异速查

  • 模型:archive_gfs vs hres
  • URL 路径:/archive_gfs/ vs /hres/
  • wrapX:true vs false
  • sourceCoords:全球边界 vs 东亚边界

2. 安装依赖

npm install leaflet leaflet-wind

3. 示例代码

import { useEffect, useRef, useState } from 'react';
import 'leaflet/dist/leaflet.css';

const API_KEY = 'YOUR_API_KEY';

// GFS 全球四角坐标:[NW, NE, SE, SW],格式为 [lon, lat]
const GFS_COORDS: [number, number][] = [
  [-180, 85.051129],  // NW
  [180, 85.051129],   // NE
  [180, -85.051129],  // SE
  [-180, -85.051129], // SW
];

// 温度色板(与 HRES 相同,可根据需要调整)
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 GfsWebglDemo() {
  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('正在加载 GFS 全球图层...');

  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;

      // GFS 全球模型:初始视角设置为全球视图
      const map = new L.Map(mapRef.current, { zoom: 2, center: [20.0, 0.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. 获取 GFS 最新时间
        const { data: [time] } = await fetch(
          `https://api.mirror-earth.com/api/vis/archive_gfs/meta?apikey=${API_KEY}&timezone=Asia/Shanghai`
        ).then(r => r.json());

        // 2. GFS 温度编码图 URL(无 tms=4326,全球温度图无需此参数)
        const url = `https://api.mirror-earth.com/api/vis/archive_gfs/temperature_2m/${time}.jpeg?size=2048&apikey=${API_KEY}`;

        // 3. 初始化全球数据源(wrapX: true 开启经度循环)
        const source = new ImageSource('temperature', {
          url,
          coordinates: GFS_COORDS,
          decodeType: DecodeType.imageWithExif,
          wrapX: true, // 全球模型必须设置为 true
        });

        const interpolateColor = TEMP_COLORS.reduce(
          (acc, [val, rgba]) => acc.concat(val, `rgba(${rgba.join(',')})`),
          [] as any[]
        );

        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('GFS 全球温度图层已加载,点击地图取值');

        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>
  );
}

4. Demo 仓库

完整可运行示例(含 HRES/GFS/ECMWF 切换)已上传至 Gitee:

  • 仓库:https://gitee.com/gfyml/me-layer-demo.git
  • React 示例:react-demo/src/components/WebglLayerDemo.tsx(选择 GFS 模型)
  • Vue 示例:vue-demo/src/components/WebglLayerDemo.vue(选择 GFS 模型)

Previous

HRES 风场粒子接入

Next

ECMWF 全球预报 WebGL 接入