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

Mapbox Vector Layer

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

Source

demos/openlayers-mapbox-vector-layer.html
<!--
  示例:矢量瓦片图层
  要点:ol.layer.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>矢量瓦片图层</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="cbWater" checked> water</label>
  <label><input type="checkbox" id="cbPark" checked> park</label>
  <label><input type="checkbox" id="cbRoad" checked> road</label>
  <span>已加载瓦片 <b id="n">0</b> 张</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 });

  /* 每个瓦片生成一组要素,属性 layer 对应 Mapbox 的 source-layer 概念 */
  function featuresForTile(z, x, y) {
    var ext = grid.getTileCoordExtent([z, x, y]);
    var w = ext[2] - ext[0];
    var out = [];

    function poly(x0, y0, x1, y1, layer, name) {
      var f = new ol.Feature({
        geometry: new ol.geom.Polygon([[
          [ext[0] + x0 * w, ext[1] + y0 * w],
          [ext[0] + x1 * w, ext[1] + y0 * w],
          [ext[0] + x1 * w, ext[1] + y1 * w],
          [ext[0] + x0 * w, ext[1] + y1 * w]
        ]]),
        layer: layer,
        name: name
      });
      out.push(f);
      return f;
    }

    var r1 = rand(x, y, z, 1), r2 = rand(x, y, z, 2), r3 = rand(x, y, z, 3);

    poly(0.05, 0.55, 0.45, 0.92, 'water', '水面');
    poly(0.55, 0.1, 0.95, 0.42, 'park', '绿地');
    poly(0.52, 0.55, 0.78, 0.78, 'building', '建筑');
    poly(0.15, 0.12, 0.48, 0.38, 'building', '建筑');

    var road = new ol.Feature({
      geometry: new ol.geom.LineString([
        [ext[0] + r1 * w, ext[1]],
        [ext[0] + r2 * w, ext[1] + w * 0.5],
        [ext[0] + r3 * w, ext[3]]
      ]),
      layer: 'road',
      name: '道路'
    });
    out.push(road);

    var label = new ol.Feature({
      geometry: new ol.geom.Point([ext[0] + w * 0.5, ext[1] + w * 0.72]),
      layer: 'place',
      name: z + '/' + x + '/' + y
    });
    out.push(label);

    return out;
  }

  var loaded = 0;

  var source = new ol.source.VectorTile({
    format: new ol.format.GeoJSON(),
    tileGrid: grid,
    attributions: '自造矢量瓦片',
    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]));
      document.getElementById('n').textContent = ++loaded;
    }
  });

  var showWater = true, showPark = true, showRoad = true;

  var layer = new ol.layer.VectorTile({
    source: source,
    style: function (feature) {
      var kind = feature.get('layer');

      if (kind === 'water') {
        if (!showWater) return null;
        return new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(86,150,200,0.75)' }) });
      }
      if (kind === 'park') {
        if (!showPark) return null;
        return new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(96,178,120,0.7)' }) });
      }
      if (kind === 'building') {
        return new ol.style.Style({
          fill: new ol.style.Fill({ color: 'rgba(190,182,168,0.9)' }),
          stroke: new ol.style.Stroke({ color: 'rgba(120,112,100,0.8)', width: 0.8 })
        });
      }
      if (kind === 'road') {
        if (!showRoad) return null;
        return new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#f6c344', width: 3 }) });
      }
      return new ol.style.Style({
        text: new ol.style.Text({
          text: feature.get('name'),
          font: '500 11px ui-monospace,monospace',
          fill: new ol.style.Fill({ color: '#44505e' }),
          stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
        })
      });
    }
  });

  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],
    view: new ol.View({ center: ol.proj.fromLonLat([116.391263, 39.907359]), zoom: 13, maxZoom: 18 }),
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  document.getElementById('cbWater').addEventListener('change', function () {
    showWater = this.checked;
    layer.changed();
  });
  document.getElementById('cbPark').addEventListener('change', function () {
    showPark = this.checked;
    layer.changed();
  });
  document.getElementById('cbRoad').addEventListener('change', function () {
    showRoad = this.checked;
    layer.changed();
  });
})();
</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 OpenLayers · EXAMPLEMapbox Vector Tiles Advanced OpenLayers · EXAMPLEMapguide Untiled