Tutorials
intermediate
JavaScript

Use Mapbox with OpenLayers

Prerequisite
Familiarity with front-end development concepts.

You can use Mapbox styles withOpenLayers. Choose the version of OpenLayers and Mapbox tool that you're working with to get started.

Getting started

There are a few things you'll need to gather before you can start working with your Mapbox maps in OpenLayers:

  • Your Mapbox access token. You can find your access tokens on your Mapbox Account page.
  • A style URL. You can find a style URL in your Mapbox account's styles page.

OpenLayers 3.x

Mapbox Studio style or Mapbox style URL

To use a Mapbox Studio style or a Mapbox style URL with OpenLayers 3.x, you'll need to reference the Mapbox Static Tiles API. You can replace the style URL mapbox/streets-v11 with your own.

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/256/{z}/{x}/{y}?access_token=YOUR_MAPBOX_ACCESS_TOKEN'
      })
    })
  ],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

Mapbox tileset ID

To use a Mapbox tileset ID with OpenLayers 3.x, you'll need to reference the Mapbox Raster Tiles API. You can replace the tileset ID mapbox.satellite with your own.

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=YOUR_MAPBOX_ACCESS_TOKEN'
      })
    })
  ],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

OpenLayers 2.x

For OpenLayers 2.x, use the OpenLayers.Layer.XYZ class. You can load a Mapbox Studio style or Mapbox style URL or a Mapbox tileset ID with OpenLayers 2.x.

Mapbox Studio style or Mapbox style URL

To use a Mapbox Studio style or a Mapbox style URL with OpenLayers 2.x, you'll need to reference the Mapbox Static Tiles API. You can replace the style URL mapbox/streets-v11 with your own.

var myLayer = new OpenLayers.Layer.XYZ(
  'My Map Layer',
  ['https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/256/${z}/${x}/${y}?access_token=YOUR_MAPBOX_ACCESS_TOKEN'],
  {
    sphericalMercator: true,
    wrapDateLine: true
  }
);
var map = new OpenLayers.Map({
  div: 'map',
  layers: [myLayer],
  center: [0, 0],
  zoom: 1
});

Mapbox tileset ID

To use a Mapbox tileset ID with OpenLayers 2.x, you'll need to reference the Mapbox Raster Tiles API. You can replace the mapbox.satellite with your own.

var myLayer = new OpenLayers.Layer.XYZ(
  'My Map Layer',
  ['https://a.tiles.mapbox.com/v4/mapbox.satellite/${z}/${x}/${y}.png?access_token=YOUR_MAPBOX_ACCESS_TOKEN'],
  {
    sphericalMercator: true,
    tileSize: new OpenLayers.Size([512, 512]),
    wrapDateLine: true
  }
);
var map = new OpenLayers.Map({
  div: 'map',
  layers: [myLayer],
  center: [0, 0],
  zoom: 1
});
Was this page helpful?