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

Mapbox Vector Tiles

Runnable OpenLayers example: Mapbox 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-mapbox-vector-tiles.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-mapbox-vector-tiles.html
<!--
  示例:矢量瓦片分层渲染
  要点:同一份矢量瓦片源挂两个图层,各按自己的过滤与缩放范围渲染
  依赖: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>矢量瓦片分层渲染</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:16px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar b{color:#16181d;font-weight:600}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <span>填充层 <b>6–18</b> 级 · 线层 <b>11–18</b> 级</span>
  <span>缩放 <b id="z">—</b>,缩到 11 级以下只看填充</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 * 374761393 + y * 668265263 + z * 2246822519 + salt * 3266489917) % 4294967296);
    h = (h ^ (h >>> 13)) * 1274126177 % 4294967296;
    return ((h ^ (h >>> 16)) % 100000) / 100000;
  }

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

  function featuresForTile(z, x, y) {
    var ext = grid.getTileCoordExtent([z, x, y]);
    var w = ext[2] - ext[0];
    var out = [];

    for (var i = 0; i < 5; i++) {
      var rx = rand(x, y, z, i + 10), ry = rand(x, y, z, i + 20), rs = rand(x, y, z, i + 30);
      var bw = 0.1 + rs * 0.14;
      var f = new ol.Feature({
        geometry: new ol.geom.Polygon([[
          [ext[0] + rx * 0.8 * w, ext[1] + ry * 0.8 * w],
          [ext[0] + (rx * 0.8 + bw) * w, ext[1] + ry * 0.8 * w],
          [ext[0] + (rx * 0.8 + bw) * w, ext[1] + (ry * 0.8 + bw) * w],
          [ext[0] + rx * 0.8 * w, ext[1] + (ry * 0.8 + bw) * w]
        ]]),
        layer: 'landuse',
        height: 20 + Math.round(rs * 120)
      });
      out.push(f);
    }

    out.push(new ol.Feature({
      geometry: new ol.geom.LineString([
        [ext[0], ext[1] + w * 0.35], [ext[0] + w, ext[1] + w * 0.62]
      ]),
      layer: 'road',
      cls: 'primary'
    }));

    out.push(new ol.Feature({
      geometry: new ol.geom.LineString([
        [ext[0] + w * 0.28, ext[1]], [ext[0] + w * 0.34, ext[3]]
      ]),
      layer: 'road',
      cls: 'secondary'
    }));

    return out;
  }

  var source = new ol.source.VectorTile({
    format: new ol.format.GeoJSON(),
    tileGrid: grid,
    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]));
    }
  });

  /* 填充层:只处理 landuse,低缩放也显示 */
  var fillLayer = new ol.layer.VectorTile({
    source: source,
    minZoom: 6,
    maxZoom: 18,
    style: function (feature) {
      if (feature.get('layer') !== 'landuse') return null;
      var h = feature.get('height');
      var t = Math.max(0, Math.min(1, (h - 20) / 120));
      return new ol.style.Style({
        fill: new ol.style.Fill({ color: 'rgba(' + Math.round(200 - t * 120) + ',' +
          Math.round(190 - t * 90) + ',' + Math.round(170 - t * 40) + ',0.9)' }),
        stroke: new ol.style.Stroke({ color: 'rgba(110,100,88,0.7)', width: 0.8 })
      });
    }
  });

  /* 线层:只在 11 级以上显示,线宽随分辨率变化 */
  var lineLayer = new ol.layer.VectorTile({
    source: source,
    minZoom: 11,
    maxZoom: 18,
    style: function (feature, resolution) {
      if (feature.get('layer') !== 'road') return null;
      var primary = feature.get('cls') === 'primary';
      return new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: primary ? '#b42318' : '#a9700f',
          width: primary ? 4 : 2,
          lineCap: 'round'
        })
      });
    }
  });

  var view = new ol.View({ center: ol.proj.fromLonLat([116.391263, 39.907359]), zoom: 9, maxZoom: 18 });

  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'}) }),
      fillLayer,
      lineLayer
    ],
    view: view,
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  function report() {
    document.getElementById('z').textContent = view.getZoom().toFixed(1);
  }
  map.on('moveend', report);
  report();
})();
</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 · EXAMPLEMapbox Vector Tiles Advanced OpenLayers · EXAMPLEMapguide Untiled OpenLayers · EXAMPLEMarker Pulse