jlord / sheetsee.js

:eyes: :chart_with_upwards_trend: Visualize Data from a Google Spreadsheet
jlord.github.io/sheetsee.js
Other
2.96k stars 884 forks source link

how to supply accessToken for mapbox? #99

Open Jmuccigr opened 8 years ago

Jmuccigr commented 8 years ago

I'm a bit confused about how to do this. The Sheetsee maps page just says to consult the mapbox docs, but sadly that doesn't help me.

TIA.

PS The supplied link to the docs yields a 404. Perhaps this is what's wanted?

Jmuccigr commented 8 years ago

Partly answering my own question here, I think.

I figured that this was the bit in the js that was responsible, starting at line 10848:

module.exports.addTileLayer = function(map, tileLayer) {
  var layer = L.mapbox.tileLayer(tileLayer)
  layer.addTo(map)
}

My first thought was that it would be easy enough just to pass it the accessToken, based on the mapbox API as described here:

module.exports.addTileLayer = function(map, tileLayer, token) {
  var layer = L.mapbox.tileLayer(tileLayer, {accessToken: token})
  layer.addTo(map)
}

Note the third argument which is the accessToken.

But that didn't work. I still got a 401 back from the mapbox server for an unauthorized request. Playing around some more, I found that the accessToken would work if the call was for L.tileLayer instead of L.mapbox.tileLayer. However that then meant (apparently) that I had to explicitly include the URL for the mapbox server. It also required an accessToken even for the included map that doesn't actually need one (jllord.n7aml2bc). What I came up with finally was this, with a little checking:

module.exports.addTileLayer = function(map, tileLayer, token) {
  if (token === '' || token === undefined) { 
     var layer = L.tileLayer('https://api.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {id: tileLayer})
    }
  else {
     var layer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {id: tileLayer, accessToken: token})
  }
  layer.addTo(map)
}

A few things to note:

  1. The full URL is now needed as the first argument, not just the tileLayer name.
  2. The function checks for an empty or an undefined (that is, missing) accessToken, and adjusts the URL accordingly, not worrying about the token.
  3. In that no-token case, I had to change the path to v3 from v4, which seems to work.

This is backwards compatible, as the first case (without a token) is what happens now.

I'm not familiar enough with mapbox or the rest of the sheetsee code to know whether this breaks other things. So far it works for me.

If it seems good, I'll put in a PR.

Jmuccigr commented 8 years ago

Thoughts?

jlord commented 8 years ago

Hi! Sorry about the delay. Unfortunately it's been a while since I've been in this code and worked with the Mapbox API (which I know has changed) so it will take me some time to re-aquaint myself.