Build applications using CARTO & Mapbox GL.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>CARTO + Mapbox GL JS</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://libs.cartocdn.com/mapbox-gl/v1.13.0/mapbox-gl.js"></script>
<link href="https://libs.cartocdn.com/mapbox-gl/v1.13.0/mapbox-gl.css" rel="stylesheet" />
</head>
<body style="margin: 0; padding: 0;">
<div id="map" style="position: absolute; top: 0; bottom: 0; width: 100%;"></div>
</body>
<script>
const layerSQL = 'SELECT the_geom_webmercator, name FROM populated_places';
const credentials = {
username: 'public',
apiKey: 'default_public',
serverUrlTemplate: 'https://{user}.carto.com'
};
const REQUEST_GET_MAX_URL_LENGTH = 2048;
const map = new mapboxgl.Map({
container: 'map',
style: 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json',
center: [0, 0],
zoom: 1
});
addCartoLayer();
async function addCartoLayer() {
const tiles = await getTiles();
map.addLayer(
{
id: 'populated_places',
type: 'circle',
source: {
type: 'vector',
tiles: tiles
},
'source-layer': 'layer0',
paint: {
'circle-color': '#EE4D5A',
'circle-stroke-color': '#FFF',
'circle-stroke-width': 1
}
},
'watername_ocean'
);
}
async function getTiles() {
const mapConfig = JSON.stringify({
version: '1.3.1',
buffersize: {mvt: 1},
layers: [
{
type: 'mapnik',
options: {
sql: layerSQL,
vector_extent: 4096,
bufferSize: 1,
version: '1.3.1'
}
}
]
});
const url = `${serverURL(credentials)}api/v1/map?${encodeParameter('api_key', credentials.apiKey)}`;
const getUrl = `${url}&${encodeParameter('config', mapConfig)}`;
let request;
if (getUrl.length < REQUEST_GET_MAX_URL_LENGTH) {
request = new Request(getUrl, {
method: 'GET',
headers: {
Accept: 'application/json'
}
});
} else {
request = new Request(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: mapConfig
});
}
const response = await fetch(request);
return (await response.json()).metadata.tilejson.vector.tiles
}
function serverURL(credentials) {
let url = credentials.serverUrlTemplate.replace(
'{user}',
credentials.username
);
if (!url.endsWith('/')) {
url += '/';
}
return url;
}
function encodeParameter(name, value) {
return `${name}=${encodeURIComponent(value)}`;
}
</script>
</html>