Loading Tile Services in Mapbox

Load vector tiles, XYZ raster tiles, and WMS in Mapbox GL JS, and handle source-layer, zoom ranges, slots, and cross-origin access.

🎯 Introduction

By the end of this article, you will be able to integrate Mapbox tilesets, third-party image tiles, and map image services, configuring sources and layers for each service type.

The WebGIS course covers the general principles of tiles, coordinate systems, and map services. This article briefly revisits them where needed and focuses on using them in Mapbox GL JS.


🧩 Load a Mapbox vector tileset

A tileset is map data divided by zoom level and geographic extent. It lets the map request only the small pieces needed for the current view instead of downloading the entire dataset.

Mapbox-hosted vector tilesets store points, lines, polygons, and their properties. Register one as a vector source using a mapbox:// URL. A tileset can contain several data layers, such as roads, buildings, and contours, so a style layer must specify which one to render through source-layer:

map.addSource('terrain', {
    type: 'vector',
    url: 'mapbox://mapbox.mapbox-terrain-v2',
})

map.addLayer({
    id: 'terrain-contours',
    type: 'line',
    source: 'terrain',
    'source-layer': 'contour',
    slot: 'middle',
    paint: {
        'line-color': '#7c3aed',
        'line-width': 1,
    },
})

Here is the rendered result. The map loads the mapbox.mapbox-terrain-v2 vector tileset and draws purple contour lines from its contour data layer:

The purple lines come from the contour layer in the vector tileset.

These three names are easy to confuse:

SettingMeaningExample
Source IDName registered for the source in the current mapterrain
Tileset URLAddress of the Mapbox-hosted resourcemapbox://mapbox.mapbox-terrain-v2
source-layerName of the data layer inside the tileset to rendercontour

With an incorrect source-layer, source requests may succeed while nothing appears. Find your tileset ID and internal layer names on the Tilesets page in Mapbox Studio.

Mapbox Studio changes periodically, so navigation and field names may differ. Follow the current interface.

🌐 Load a self-hosted MVT service

MVT (Mapbox Vector Tile) is a common vector tile format that defines how a tile stores points, lines, polygons, and properties. PBF (Protocol Buffers) is the binary encoding commonly used for this data, providing compact files. Tile URLs therefore often end in .pbf.

A self-hosted MVT service can provide a URL template containing placeholders. {z} is the zoom level, while {x} and {y} are the column and row at that level. Mapbox fills these in automatically for the current viewport.

minzoom is the lowest zoom level the service provides, and maxzoom is the highest level with actual data. They prevent Mapbox from requesting levels the service does not have:

map.addSource('roads', {
    type: 'vector',
    tiles: ['https://example.com/tiles/roads/{z}/{x}/{y}.pbf'],
    minzoom: 6,
    maxzoom: 14,
})

map.addLayer({
    id: 'road-lines',
    type: 'line',
    source: 'roads',
    'source-layer': 'roads',
    slot: 'middle',
    paint: {
        'line-color': '#2563eb',
        'line-width': 2,
    },
})

Here, 6 starts loading at level 6, while 14 means closer views continue using level-14 tiles without gaining finer data. Layers also support these fields to control their visible zoom ranges.


🖼 Load XYZ raster tiles

Raster tiles are prerendered images, commonly PNG, JPEG, or WebP. XYZ organizes tile URLs as {z}/{x}/{y}, where z is zoom, x is the column, and y is the row. In Mapbox, use a raster source and a raster layer.

tileSize specifies the intended image size in pixels; attribution supplies the data credit that must remain visible on the map:

map.addSource('raster-basemap', {
    type: 'raster',
    tiles: ['https://tile.example.com/{z}/{x}/{y}.png'],
    tileSize: 256,
    minzoom: 0,
    maxzoom: 18,
    attribution: 'Map data provider',
})

map.addLayer({
    id: 'raster-basemap-layer',
    type: 'raster',
    source: 'raster-basemap',
    slot: 'bottom',
    paint: {
        'raster-opacity': 0.8,
    },
})

tileSize must match the service; common values are 256 and 512. TMS is another tile numbering scheme with the y-axis reversed relative to XYZ. For TMS services, add scheme: 'tms' to the source.

Tile services may restrict concurrency, caching, and allowed domains. Read their terms before integration and retain required attribution.

The example below uses Mapbox-hosted satellite imagery as a raster source. It uses the same raster layer as an XYZ service; only the data address differs, using mapbox://mapbox.satellite:

A raster source loads satellite imagery, and a raster layer displays it.

📡 Use WMS as a raster layer

WMS (Web Map Service) generates map images on the server for a requested extent, set of layers, and image format. A GetMap request asks the server to return those layers for that extent.

Mapbox GL JS has no dedicated WMS source type, but a GetMap URL can serve as a raster source. Mapbox replaces {bbox-epsg-3857} with each tile's bounding box in Web Mercator coordinates:

const wmsUrl = [
    'https://example.com/geoserver/wms',
    '?service=WMS',
    '&version=1.1.1',
    '&request=GetMap',
    '&layers=workspace:areas',
    '&styles=',
    '&format=image/png',
    '&transparent=true',
    '&srs=EPSG:3857',
    '&bbox={bbox-epsg-3857}',
    '&width=256',
    '&height=256',
].join('')

map.addSource('area-wms', {
    type: 'raster',
    tiles: [wmsUrl],
    tileSize: 256,
})

map.addLayer({
    id: 'area-wms-layer',
    type: 'raster',
    source: 'area-wms',
    slot: 'middle',
})

srs identifies the request's coordinate reference system. EPSG:3857 identifies Web Mercator, a projection commonly used for web maps. The example uses WMS 1.1.1 so bounding-box order matches Mapbox's placeholder. Before changing version or coordinate system, verify the service's axis order and supported extent.


🪤 Requests succeed but nothing appears

Check the following in order:

  1. Confirm tile requests return 200 in the browser's network panel.
  2. For vector tiles, match source-layer to the service's internal layer name.
  3. Check that the map zoom falls within both source and layer zoom ranges.
  4. Verify the coordinate reference system, XYZ/TMS scheme, and tileSize.
  5. Check whether basemap layers cover the application layer; choose an appropriate slot with Standard.
  6. For cross-origin errors, check that the tile server allows the current website to read its resources.

CORS (Cross-Origin Resource Sharing) is the browser mechanism through which servers specify which websites may read resources. The tile server must allow your website's origin in its response headers. Otherwise, even if the request reaches the server, the browser will not expose the response to Mapbox.

Listen for resource errors during initialization to find clues about failed requests:

map.on('error', (event) => {
    console.error('Failed to load map resource', event.error)
})

🧾 Summary

  • Mapbox-hosted tilesets use mapbox:// URLs; self-hosted services can use tile URL templates.
  • Vector tile layers require the correct source-layer.
  • XYZ images use a raster source; TMS services also need scheme: 'tms'.
  • Integrate WMS with a GetMap request containing {bbox-epsg-3857}.
  • Common checks include minzoom, maxzoom, tileSize, CORS, and layer placement.

❓ Questions and answers

Q1: Why is a vector layer empty even though the source loaded?

Check source-layer first. It must match the data layer name inside the vector tiles, not the source ID or the page's style layer ID.

Q2: Can I load WMTS directly?

WMTS (Web Map Tile Service) provides pre-generated tiles. If it offers a compatible Web Mercator XYZ URL, use a raster or vector tile source. For parameter-based URLs, construct the correct template using the service's tile matrix rules.

Q3: Why can't Mapbox configuration fix a CORS error?

The tile server supplies CORS response headers. Once the browser blocks a response, Mapbox cannot read it. Configure the server to allow the website's origin.


🧪 Exercises

  1. Add an XYZ image service as a raster source with the correct tileSize.
  2. Add a line layer for an MVT service, using its actual source-layer.
// Write your code here

🎉 You now know how to integrate common tile services into Mapbox!