Vector tiles in OpenLayers
Vector tiles maps are made of mathematical interpretations of geometric features such as points, curves or polygons. Vector tiles are rendered on the client’s side with a style, which is a small text file that defines how certain map elements look and how they are displayed. Read more about Vector tiles in this article What are vector tiles and why you should care?
Vector tiles ol-mapbox-style (plugin)
Vector tiles can be displayed in OpenLayers using the ol-mapbox-style plugin
NPM module setup
npm install --save ol ol-mapbox-style
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Attribution from 'ol/control/Attribution.js';
import { defaults as defaultControls } from 'ol/control/defaults.js';
import { fromLonLat } from 'ol/proj.js';
import 'ol/ol.css';
import { apply } from 'ol-mapbox-style';
const key = 'YOUR_MAPTILER_API_KEY_HERE';
const styleJson = `https://api.maptiler.com/maps/streets-v4/style.json?key=${key}`;
const attribution = new Attribution({
collapsible: false,
});
const map = new Map({
target: 'map',
controls: defaultControls({attribution: false}).extend([attribution]),
view: new View({
constrainResolution: true,
center: fromLonLat([0, 0]),
zoom: 2
})
});
apply(map, styleJson);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Vector tiles in OpenLayers | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map">
<a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
</div><p><a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a></p>
<script type="module" src="./main.js"></script>
</body>
</html>
#map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.
Summary
The easiest way to work with vector tiles in OpenLayers is to use the ol-mapbox-style plugin. OpenLayers supports vector tiles natively but you have to create a specific style. Check out the example.