Skip to content

自定义 Canvas 瓦片 ​

自定义 Canvas 瓦片示例。 图层 vectortiles tms canvas

WARNING

矢量瓦片来自外部地址 ahocevar.com/geoserver,已改为通过代理 pbf.cxvh.com 访问,服务不可用时无数据。

黑色网格瓦片在客户端使用 HTML5 canvas 生成。显示的 TMS 瓦片坐标由自定义的 TMS 模板、矢量瓦片数据源的 512 像素瓦片网格以及矢量瓦片的 zDirection 设置生成。请注意国家多边形可能会被分割到不同瓦片中,矢量标注也可能在每个瓦片中重复出现。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import MVT from 'ol/format/MVT.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorTileLayer from 'ol/layer/VectorTile.js';
import TileDebug from 'ol/source/TileDebug.js';
import VectorTileSource from 'ol/source/VectorTile.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
import Text from 'ol/style/Text.js';

const style = new Style({
  fill: new Fill({
    color: 'rgba(255, 255, 255, 0.6)',
  }),
  stroke: new Stroke({
    color: '#319FD3',
    width: 1,
  }),
  text: new Text({
    font: '12px Calibri,sans-serif',
    fill: new Fill({
      color: '#000',
    }),
    stroke: new Stroke({
      color: '#fff',
      width: 3,
    }),
  }),
});

const vtLayer = new VectorTileLayer({
  declutter: true,
  source: new VectorTileSource({
    maxZoom: 15,
    format: new MVT(),
    url:
      'https://ahocevar.com/geoserver/gwc/service/tms/1.0.0/' +
      'ne:ne_10m_admin_0_countries@EPSG%3A900913@pbf/{z}/{x}/{-y}.pbf',
  }),
  style: function (feature) {
    style.getText().setText(feature.get('name'));
    return style;
  },
});

const debugLayer = new TileLayer({
  source: new TileDebug({
    template: 'z:{z} x:{x} y:{-y}',
    projection: vtLayer.getSource().getProjection(),
    tileGrid: vtLayer.getSource().getTileGrid(),
    zDirection: 1,
  }),
});

const map = new Map({
  layers: [vtLayer, debugLayer],
  target: 'map',
  view: new View({
    center: [0, 6000000],
    zoom: 4,
  }),
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>自定义 Canvas 瓦片</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "canvas-tiles-tms",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}