Making it easy to reuse open source mapbox-gl-js styles that need tokens
Problem: To reuse mapbox-gl styles with sources other than Mapbox, for example maptiler or thunderforest requires modifying the style.json
to insert your own keys/tokens
Solution: A simple function to transform the http requests at runtime to add in your tokens.
To install
npm install orangemug/mapbox-gl-tokens
Via <script/>
tags (work in progress)
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css' rel='stylesheet' />
<!-- Include the library -->
<script src='https://orangemug.github.io/mapbox-gl-tokens/mapbox-gl-tokens.min.js'></script>
</head>
<body>
<div id='map'></div>
<script>
var map = new mapboxgl.Map({
container: 'map',
style: 'https://maputnik.github.io/osm-liberty/style.json',
/* Transform the requests adding in the tokens */
transformRequest: mapboxGlTokens({
tilehosting: "INSERT_TOKEN_HERE",
thunderforest: "INSERT_TOKEN_HERE"
})
});
</script>
</body>
</html>
Via npm
const mapboxGlTokens = require("mapbox-gl-tokens");
const tokens = {
tilehosting: "TOKEN",
thunderforest: "TOKEN"
};
const map = new mapboxgl.Map({
container: 'map',
style: 'https://maputnik.github.io/osm-liberty/style.json',
transformRequest: mapboxGlTokens(tokens),
});
The library also accepts a second parameter, which can further transform the request.
mapboxGlTokens(tokens, function(url, resourceType) {
// Transform the request in the normal way...
return {
url: url
}
});
See https://www.mapbox.com/mapbox-gl-js/api#map options.transformRequest
for full details.