Shared Cache header
by felixp
HTML
<!DOCTYPE html>
<html>
<head>
<title>Shared Cache header</title>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.js"></script>
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.4.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/[email protected]/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/[email protected]/dist.min.js"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>
CSS
/* Always set the map height explicitly to define the size of the div element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
// Access tokens
mapboxgl.accessToken = 'pk.eyJ1IjoiY2FydG9kYmluYyIsImEiOiJja202bHN2OXMwcGYzMnFrbmNkMzVwMG5rIn0.Zb3J4JTdJS-oYNXlR3nvnQ';
const accessTokenCarto = 'eyJhbGciOiJIUzI1NiJ9.eyJhIjoiYWNfbHFlM3p3Z3UiLCJqdGkiOiI1YjI0OWE2ZCJ9.Y7zB30NJFzq5fPv8W5nkoH5lPXFWQP0uywDtqUg8y8c';
// Map instantiation URL
const apiBaseUrl = 'https://gcp-us-east1.api.carto.com';
const connectionName = 'bqconn';
const tileset = 'cartobq.public_account.nyc_taxi_points_demo_id';
const mapUrl = `${apiBaseUrl}/v3/maps/${connectionName}/tileset?name=${tileset}&v=3.1`;
const Authorization = `Bearer ${accessTokenCarto}`;
// Get TileJSON URL from API
async function fetchTilejsonUrl(url, headers) {
const response = await fetch(url, {headers});
const data = await response.json();
const {tilejson} = data;
return tilejson.url[0];
}
// Transform all CARTO API requests to include access token
function transformRequest(url, resourceType) {
if (url.indexOf(apiBaseUrl) !== 0) {
return {url}
}
return {url, headers: {Authorization}};
}
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-73.8, 40.73],
zoom: 9,
transformRequest
});
map.on('load', async () => {
const url = await fetchTilejsonUrl(mapUrl, {Authorization});
map.addLayer({
'id': 'taxi-data',
'type': 'circle',
'source': {
'type': 'vector',
url
},
'source-layer': 'default',
'paint': {
'circle-radius': 2,
'circle-color': [
'step',
['get', 'aggregated_total'],
'#009392',
10,
'#39b185',
1e2,
'#9ccb86',
1e3,
'#e9e29c',
1e4,
'#eeb479',
1e5,
'#e88471',
1e6,
'#cf597e'
]
}
});
});