Osm Vector Tiles
Runnable OpenLayers example: Osm Vector Tiles. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:OSM 矢量瓦片
要点:矢量瓦片里装的是要素而非图片,样式可以按类别随时切换
依赖: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>OSM 矢量瓦片</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 input[type=range]{width:110px}
.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> 水系</label>
<label><input type="checkbox" id="cbRoad" checked> 道路</label>
<label><input type="checkbox" id="cbLabel" checked> 地名</label>
<label for="op">底图不透明度 <b id="opv">0.35</b></label>
<input type="range" id="op" min="0" max="1" step="0.05" value="0.35">
</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 * 1597334677 + y * 3812015801 + z * 2798796415 + salt * 2654435761) % 4294967296);
h = (h ^ (h >>> 14)) * 1597334677 % 4294967296;
return ((h ^ (h >>> 17)) % 100000) / 100000;
}
var grid = ol.tilegrid.createXYZ({ tileSize: 512, maxZoom: 18 });
/* 生成 OSM 风格的三类要素:水系面、道路线、地名点 */
function featuresForTile(z, x, y) {
var ext = grid.getTileCoordExtent([z, x, y]);
var w = ext[2] - ext[0];
var out = [];
var r1 = rand(x, y, z, 1), r2 = rand(x, y, z, 2);
out.push(new ol.Feature({
geometry: new ol.geom.Polygon([[
[ext[0], ext[1] + w * (0.15 + r1 * 0.3)],
[ext[0] + w, ext[1] + w * (0.1 + r2 * 0.3)],
[ext[0] + w, ext[1] + w * (0.45 + r2 * 0.2)],
[ext[0], ext[1] + w * (0.5 + r1 * 0.2)]
]]),
layer: 'water'
}));
out.push(new ol.Feature({
geometry: new ol.geom.LineString([
[ext[0], ext[1] + w * 0.3], [ext[0] + w * 0.5, ext[1] + w * 0.55], [ext[0] + w, ext[1] + w * 0.4]
]),
layer: 'road', cls: 'motorway'
}));
out.push(new ol.Feature({
geometry: new ol.geom.LineString([
[ext[0] + w * 0.2, ext[1]], [ext[0] + w * 0.3, ext[1] + w]
]),
layer: 'road', cls: 'residential'
}));
out.push(new ol.Feature({
geometry: new ol.geom.Point([ext[0] + w * (0.3 + r1 * 0.4), ext[1] + w * (0.6 + r2 * 0.3)]),
layer: 'place',
name: z + '/' + x + '/' + y
}));
return out;
}
var source = new ol.source.VectorTile({
format: new ol.format.GeoJSON(),
tileGrid: grid,
attributions: '自造矢量瓦片 · OSM 风格',
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 show = { water: true, road: true, place: true };
var layer = new ol.layer.VectorTile({
source: source,
style: function (feature) {
var kind = feature.get('layer');
if (!show[kind]) return null;
if (kind === 'water') {
return new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(140,190,225,0.85)' }) });
}
if (kind === 'road') {
var motorway = feature.get('cls') === 'motorway';
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: motorway ? '#e8a33d' : '#9aa3af',
width: motorway ? 4 : 2
})
});
}
return new ol.style.Style({
text: new ol.style.Text({
text: feature.get('name'),
font: '600 12px sans-serif',
fill: new ol.style.Fill({ color: '#2c3440' }),
stroke: new ol.style.Stroke({ color: '#ffffff', width: 3.5 })
})
});
}
});
var base = 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'}), opacity: 0.35 });
var map = new ol.Map({
target: 'map',
layers: [base, layer],
view: new ol.View({ center: ol.proj.fromLonLat([116.391263, 39.907359]), zoom: 12, maxZoom: 18 }),
controls: ol.control.defaults.defaults({ rotate: false })
});
['water', 'road', 'place'].forEach(function (kind) {
var id = kind === 'place' ? 'cbLabel' : 'cb' + kind.charAt(0).toUpperCase() + kind.slice(1);
document.getElementById(id).addEventListener('change', function () {
show[kind] = this.checked;
layer.changed();
});
});
document.getElementById('op').addEventListener('input', function () {
var v = Number(this.value);
document.getElementById('opv').textContent = v.toFixed(2);
base.setOpacity(v);
});
})();
</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.