CARTO + Mapbox GL JS

CARTO + Mapbox GL JS

Hello World

This example shows how to create your first map using CARTO and Mapbox GL JS.

 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
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>CARTO 3 + Mapbox GL JS - Hello World</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
  <link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet">
  <script src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"></script>
  <script src="https://unpkg.com/deck.gl@^8.5.0/dist.min.js"></script>
  <script src="https://unpkg.com/@deck.gl/carto@^8.5.0/dist.min.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoiY2FydG9kYmluYyIsImEiOiJja202bHN2OXMwcGYzMnFrbmNkMzVwMG5rIn0.Zb3J4JTdJS-oYNXlR3nvnQ';
    var map = new mapboxgl.Map({
      container: 'map', 
      style: 'mapbox://styles/mapbox/light-v10', 
      center: [0, 0], 
      zoom: 1 
    });

    deck.carto.setDefaultCredentials({
      apiBaseUrl: 'https://gcp-us-east1.api.carto.com',
      apiVersion: deck.carto.API_VERSIONS.V3,
      accessToken: 'eyJhbGciOiJIUzI1NiJ9.eyJhIjoiYWNfbHFlM3p3Z3UiLCJqdGkiOiI1YjI0OWE2ZCJ9.Y7zB30NJFzq5fPv8W5nkoH5lPXFWQP0uywDtqUg8y8c'
    });

    map.on('load', async () => {
      // Fetch Data from CARTO
      const data =  await deck.carto.getData({
        type: deck.carto.MAP_TYPES.QUERY,
        source: `SELECT geom, name FROM cartobq.public_account.populated_places`,
        connection: 'bqconn',
        format: deck.carto.FORMATS.GEOJSON
      });
      map.addSource('populated-places', {
        'type': 'geojson',
        'data': data
      });
      map.addLayer({
        'id': 'populated-places',
        'type': 'circle',
        'source': 'populated-places',
        'paint': {
          'circle-radius': 3,
          'circle-color': '#FF0000',
          'circle-stroke-color': 'white',
          'circle-stroke-width': 1,
          'circle-opacity': 0.5
        }
      });
    });

  </script>

</body>

</html>