You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Leaflet中使用Ordnance Survey地图切片?

在React中集成Ordnance Survey(OS)WMTS地图

依赖安装

首先安装所需的npm包:

npm install react-leaflet leaflet proj4 proj4leaflet

完整React组件代码

import React from 'react';
import { MapContainer, TileLayer } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import proj4 from 'proj4';
import 'proj4leaflet';

// 替换为你的OS API密钥
const API_KEY = 'INSERT_API_KEY_HERE';

// 配置EPSG:27700(英国国家格网)坐标系
const crs = new L.Proj.CRS(
  'EPSG:27700',
  '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs',
  {
    resolutions: [896.0, 448.0, 224.0, 112.0, 56.0, 28.0, 14.0, 7.0, 3.5, 1.75],
    origin: [-238375.0, 1376256.0],
  }
);

// 坐标转换:EPSG:27700 → EPSG:4326(WGS84)
const transformCoords = (arr) => proj4('EPSG:27700', 'EPSG:4326', arr).reverse();

const OSMap = () => {
  // WMTS请求参数
  const wmtsParams = {
    key: API_KEY,
    service: 'WMTS',
    request: 'GetTile',
    version: '2.0.0',
    height: 256,
    width: 256,
    outputFormat: 'image/png',
    style: 'default',
    layer: 'Leisure_27700',
    tileMatrixSet: 'EPSG:27700',
    tileMatrix: '{z}',
    tileRow: '{y}',
    tileCol: '{x}',
  };

  // 生成WMTS瓦片URL
  const queryString = new URLSearchParams(wmtsParams).toString();
  const tileUrl = `https://api.os.uk/maps/raster/v1/wmts?${queryString}`;

  return (
    <div style={{ height: '100vh', width: '100%' }}>
      <MapContainer
        center={transformCoords([337297, 503695])}
        zoom={7}
        minZoom={0}
        maxZoom={9}
        crs={crs}
        maxBounds={[
          transformCoords([-238375.0, 0.0]),
          transformCoords([900000.0, 1376256.0]),
        ]}
        attributionControl={false}
        style={{ height: '100%', width: '100%' }}
      >
        <TileLayer url={tileUrl} />
      </MapContainer>
    </div>
  );
};

export default OSMap;

关键注意事项

  • 样式设置:必须给地图容器(外层div和MapContainer)设置明确的宽高,否则地图会因无尺寸而无法显示
  • 坐标系复用:直接沿用原代码中的EPSG:27700配置,确保OS瓦片的投影匹配
  • 参数构建:用URLSearchParams自动处理参数拼接,避免手动拼接字符串的错误
  • API密钥:记得将INSERT_API_KEY_HERE替换为你自己的OS Data Hub API密钥

内容的提问来源于stack exchange,提问作者React Beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:30:57