Mapbox Layer
Runnable OpenLayers example: Mapbox Layer. 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
<!--
示例:Mapbox 样式图层
要点:把样式 JSON 的 layers 数组编译成图层 + 过滤器 + 绘制属性
依赖: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>Mapbox 样式图层</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}
#map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
<label><input type="checkbox" id="cbPark" checked> 绿地 fill</label>
<label><input type="checkbox" id="cbRoad" checked> 道路 line</label>
<label><input type="checkbox" id="cbHub" checked> 枢纽 circle</label>
<span id="layers">3 个样式层</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;
}
var fromLonLat = ol.proj.fromLonLat;
/* 数据源:一份内联 GeoJSON,字段 kind 决定进哪个样式层 */
var data = {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { kind: 'park', name: '北海公园' },
geometry: { type: 'Polygon', coordinates: [[[116.375, 39.935], [116.395, 39.935], [116.395, 39.918], [116.375, 39.918], [116.375, 39.935]]] } },
{ type: 'Feature', properties: { kind: 'park', name: '天坛公园' },
geometry: { type: 'Polygon', coordinates: [[[116.405, 39.888], [116.425, 39.888], [116.425, 39.872], [116.405, 39.872], [116.405, 39.888]]] } },
{ type: 'Feature', properties: { kind: 'route', name: '环路' },
geometry: { type: 'LineString', coordinates: [[116.30, 39.90], [116.36, 39.94], [116.44, 39.95], [116.505, 39.90], [116.44, 39.855], [116.352, 39.868], [116.30, 39.90]] } },
{ type: 'Feature', properties: { kind: 'hub', name: '北京站' }, geometry: { type: 'Point', coordinates: [116.427, 39.903] } },
{ type: 'Feature', properties: { kind: 'hub', name: '西站' }, geometry: { type: 'Point', coordinates: [116.322, 39.895] } }
]
};
var styleJSON = {
version: 8,
sources: { local: { type: 'geojson', data: data } },
layers: [
{ id: 'park', type: 'fill', source: 'local', filter: ['==', 'kind', 'park'],
paint: { 'fill-color': '#2f9e6e', 'fill-opacity': 0.6, 'fill-outline-color': '#166b46' } },
{ id: 'route', type: 'line', source: 'local', filter: ['==', 'kind', 'route'],
paint: { 'line-color': '#b42318', 'line-width': 3.5 } },
{ id: 'hub', type: 'circle', source: 'local', filter: ['==', 'kind', 'hub'],
paint: { 'circle-radius': 7, 'circle-color': '#1f5fd0', 'circle-stroke-color': '#ffffff', 'circle-stroke-width': 2 } }
]
};
/* 只实现用到的过滤表达式:== 与 in */
function compileFilter(expr) {
if (!expr) return function () { return true; };
if (expr[0] === '==') {
return function (f) { return f.get(expr[1]) === expr[2]; };
}
if (expr[0] === 'in') {
var list = expr.slice(2);
return function (f) { return list.indexOf(f.get(expr[1])) >= 0; };
}
return function () { return true; };
}
/* 把 paint 属性翻成 ol.style,按 Mapbox 的键名对应 */
function compileStyle(def) {
var paint = def.paint || {};
return new ol.style.Style({
fill: def.type === 'fill' ? new ol.style.Fill({
color: paint['fill-color'] || 'rgba(0,0,0,0.2)'
}) : undefined,
stroke: def.type === 'fill' ? new ol.style.Stroke({
color: paint['fill-outline-color'] || 'rgba(0,0,0,0.4)',
width: 1
}) : def.type === 'line' ? new ol.style.Stroke({
color: paint['line-color'] || '#333',
width: paint['line-width'] || 1
}) : undefined,
image: def.type === 'circle' ? new ol.style.Circle({
radius: paint['circle-radius'] || 5,
fill: new ol.style.Fill({ color: paint['circle-color'] || '#333' }),
stroke: new ol.style.Stroke({
color: paint['circle-stroke-color'] || 'transparent',
width: paint['circle-stroke-width'] || 0
})
}) : undefined
});
}
var allFeatures = new ol.format.GeoJSON().readFeatures(data, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
var compiled = styleJSON.layers.map(function (def) {
var pass = compileFilter(def.filter);
var source = new ol.source.Vector({ features: allFeatures.filter(pass) });
return new ol.layer.Vector({
source: source,
style: compileStyle(def),
properties: { id: def.id }
});
});
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'}) })].concat(compiled),
view: new ol.View({ center: fromLonLat([116.40, 39.905]), zoom: 12 }),
controls: ol.control.defaults.defaults({ rotate: false })
});
function bind(id, layer) {
document.getElementById(id).addEventListener('change', function () {
layer.setVisible(this.checked);
});
}
bind('cbPark', compiled[0]);
bind('cbRoad', compiled[1]);
bind('cbHub', compiled[2]);
})();
</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.