Rick R.
Rick R.

Reputation: 179

How to display Mapbox tile layer

I'm attempting to use this simple example from LeafletJS but am unable to get the layer to display using my Mapbox public key. The map displays a grey background with my sample marker and pop up.

var map = L.map('map').setView([39.5, -105.5], 7);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'test.project',
accessToken: 'copied.and.pasted.my.mapbox.key.here'
}).addTo(mymap);

L.marker([39.5, -105.5]).addTo(map)
.bindPopup('This is my first marker!')
.openPopup();

Upvotes: 1

Views: 3253

Answers (1)

chrki
chrki

Reputation: 6323

You are calling .addTo(mymap); on the tilelayer, but your map object is map. Use this: .addTo(map);

You might also have to change the URL a bit. Following the documentation here I created a map based on a style:

var map = L.map('map').setView([39.5, -105.5], 7);

L.tileLayer('https://api.tiles.mapbox.com/styles/v1/{username}/{id}/tiles/{tileSize}/{z}/{x}/{y}?access_token={accessToken}', {
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  maxZoom: 18,
  username: 'mapbox username',
  id: 'mapbox style id',
  accessToken: 'mapbox access token',
  tileSize: 512, 
  zoomOffset: -1
}).addTo(map);

L.marker([39.5, -105.5]).addTo(map)
  .bindPopup('This is my first marker!')
  .openPopup();

If you want to retrieve tiles for a certain tileset use this (documentation):

L.tileLayer('https://api.mapbox.com/v4/{tilesetId}/{z}/{x}/{y}.png?access_token={accessToken}', {
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  maxZoom: 18,
  accessToken: 'mapbox access token',
  tilesetId: 'mapbox tileset id'
}).addTo(map);

tilesetId has the form of username.id, it's not your project's name, you can find it in the editor/Studio.

Upvotes: 1

Related Questions