Example of a vector tiles map rendered using WebGL.
A simple map showing Mapbox vector tiles, rendered using WebGL. Note: Make sure to get your own Mapbox API key when using this example. No map will be visible when the API key has expired.
import MVT from 'ol/format/MVT.js';
import Map from 'ol/Map.js';
import VectorTile from 'ol/layer/VectorTile.js';
import VectorTileSource from 'ol/source/VectorTile.js';
import View from 'ol/View.js';
import WebGLVectorTileLayerRenderer from 'ol/renderer/webgl/VectorTileLayer.js';
import {Fill, Icon, Stroke, Style, Text} from 'ol/style.js';
import {asArray} from 'ol/color.js';
import {packColor, parseLiteralStyle} from 'ol/webgl/styleparser.js';
const key =
'Your Mapbox access token from https://mapbox.com/ here';
const result = parseLiteralStyle({
'fill-color': ['get', 'fillColor'],
'stroke-color': ['get', 'strokeColor'],
'stroke-width': ['get', 'strokeWidth'],
'circle-radius': 4,
'circle-fill-color': '#777',
});
class WebGLVectorTileLayer extends VectorTile {
createRenderer() {
return new WebGLVectorTileLayerRenderer(this, {
style: {
builder: result.builder,
attributes: {
fillColor: {
size: 2,
callback: (feature) => {
const style = this.getStyle()(feature, 1)[0];
const color = asArray(style?.getFill()?.getColor() || '#eee');
return packColor(color);
},
},
strokeColor: {
size: 2,
callback: (feature) => {
const style = this.getStyle()(feature, 1)[0];
const color = asArray(style?.getStroke()?.getColor() || '#eee');
return packColor(color);
},
},
strokeWidth: {
size: 1,
callback: (feature) => {
const style = this.getStyle()(feature, 1)[0];
return style?.getStroke()?.getWidth() || 0;
},
},
},
},
});
}
}
const map = new Map({
layers: [
new WebGLVectorTileLayer({
source: new VectorTileSource({
attributions:
'© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> ' +
'© <a href="https://www.openstreetmap.org/copyright">' +
'OpenStreetMap contributors</a>',
format: new MVT(),
url:
'https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
'{z}/{x}/{y}.vector.pbf?access_token=' +
key,
}),
style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text),
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGL Vector Tiles Layer</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="https://openlayers.org/en/v9.2.2/examples/resources/mapbox-streets-v6-style.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "webgl-vector-tiles",
"dependencies": {
"ol": "9.2.2"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}