Atlaslog
Atlaslog / Examples / OpenLayers / Ogc Vector Tiles
OpenLayers · Runnable Example

Ogc Vector Tiles

Runnable OpenLayers example: Ogc Vector Tiles. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All OpenLayers examples
/demos/openlayers-ogc-vector-tiles.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-ogc-vector-tiles.html
<!--
  示例:OGC 矢量瓦片
  要点:VectorTile 源按瓦片坐标生成要素,瓦片边界单独一层便于核对
  依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>OGC 矢量瓦片</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#16181d}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  .bar b{color:#16181d;font-weight:600}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <label><input type="checkbox" id="bounds"> 显示瓦片边界</label>
  <span>瓦片 <b id="tid">—</b> 要素数 <b id="fc">—</b></span>
  <span>点击瓦片查看统计</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';
  if (!window.ol) {
    document.getElementById('map').textContent = 'OpenLayers 加载失败,请检查 cdn.jsdelivr.net 是否可访问';
    return;
  }

  function rand(x, y, z, salt) {
    var h = Math.abs((x * 2654435761 + y * 40503 + z * 2246822519 + salt * 3266489917) % 4294967296);
    h = (h ^ (h >>> 15)) * 1274126177 % 4294967296;
    return ((h ^ (h >>> 16)) % 100000) / 100000;
  }

  var grid = ol.tilegrid.createXYZ({ tileSize: 512, maxZoom: 18 });
  var counts = {};

  function featuresForTile(z, x, y) {
    var ext = grid.getTileCoordExtent([z, x, y]);
    var w = ext[2] - ext[0];
    var n = 4 + Math.floor(rand(x, y, z, 99) * 5);
    var out = [];

    for (var i = 0; i < n; i++) {
      var cx = ext[0] + rand(x, y, z, i) * w;
      var cy = ext[1] + rand(x, y, z, i + 50) * w;
      var r = w * (0.03 + rand(x, y, z, i + 80) * 0.05);
      out.push(new ol.Feature({
        geometry: new ol.geom.Circle([cx, cy], r),
        kind: rand(x, y, z, i + 7) > 0.5 ? 'a' : 'b'
      }));
    }

    counts[z + '/' + x + '/' + y] = n + 1;

    out.push(new ol.Feature({
      geometry: new ol.geom.Circle([ext[0] + w * 0.5, ext[1] + w * 0.5], w * 0.12),
      kind: 'c'
    }));

    return out;
  }

  var source = new ol.source.VectorTile({
    format: new ol.format.GeoJSON(),
    tileGrid: grid,
    attributions: '自造矢量瓦片 · 模板 /{z}/{y}/{x}',
    tileUrlFunction: function (tc) { return tc.join('/'); },
    tileLoadFunction: function (tile, url) {
      var p = url.split('/').map(Number);
      tile.setFeatures(featuresForTile(p[0], p[1], p[2]));
    }
  });

  var layer = new ol.layer.VectorTile({
    source: source,
    style: function (feature) {
      var kind = feature.get('kind');
      var color = kind === 'a' ? 'rgba(31,95,208,0.7)'
        : kind === 'b' ? 'rgba(47,158,110,0.7)'
          : 'rgba(250,193,86,0.85)';
      return new ol.style.Style({
        fill: new ol.style.Fill({ color: color }),
        stroke: new ol.style.Stroke({ color: 'rgba(255,255,255,0.8)', width: 1.2 })
      });
    }
  });

  var boundsSource = new ol.source.Vector();
  var boundsLayer = new ol.layer.Vector({ source: boundsSource, visible: false, zIndex: 30 });

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }),
      layer,
      boundsLayer
    ],
    view: new ol.View({ center: ol.proj.fromLonLat([116.391263, 39.907359]), zoom: 12, maxZoom: 18 }),
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  /* 画出当前级别可见瓦片的边界,便于核对要素是否落在瓦片范围内 */
  function drawBounds() {
    boundsSource.clear();
    if (!boundsLayer.getVisible()) return;

    var z = Math.round(map.getView().getZoom());
    var range = grid.getTileRangeForExtentAndZ(map.getView().calculateExtent(map.getSize()), z);

    for (var tx = range.minX; tx <= range.maxX; tx++) {
      for (var ty = range.minY; ty <= range.maxY; ty++) {
      var tc = [z, tx, ty];
      var ext = grid.getTileCoordExtent(tc);
      var f = new ol.Feature({
        geometry: new ol.geom.Polygon([[
          [ext[0], ext[1]], [ext[2], ext[1]], [ext[2], ext[3]], [ext[0], ext[3]]
        ]])
      });
      f.setStyle(new ol.style.Style({
        stroke: new ol.style.Stroke({ color: 'rgba(180,35,24,0.8)', width: 1.5 }),
        text: new ol.style.Text({
          text: tc.join('/'),
          font: '500 11px ui-monospace,monospace',
          fill: new ol.style.Fill({ color: '#b42318' }),
          stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
        })
      }));
      boundsSource.addFeature(f);
      }
    }
  }

  document.getElementById('bounds').addEventListener('change', function () {
    boundsLayer.setVisible(this.checked);
    drawBounds();
  });

  map.on('moveend', drawBounds);

  map.on('singleclick', function (evt) {
    var z = Math.round(map.getView().getZoom());
    var tc = grid.getTileCoordForCoordAndZ(evt.coordinate, z);
    if (!tc) return;
    var key = tc.join('/');
    document.getElementById('tid').textContent = key;
    document.getElementById('fc').textContent = counts[key] || '未加载';
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More OpenLayers examples

OpenLayers · EXAMPLEOgc Vector Tiles Geographic OpenLayers · EXAMPLEOsm Vector Tiles OpenLayers · EXAMPLEOverlay