Build a public application

Create a basic web application in CARTO compatible with any Javascript Framework

Here you will learn the basic concepts required to create a public web application using CARTO, compatible with any Javascript Development Framework. With CARTO you don't need to be a geospatial expert to develop a geospatial application, so if you're a web developer you shouldn't have any issues following this guide.

After completing this guide you will be familiar with the following concepts:

  • Scaffolding your application.

  • Adding a basemap

  • Creating an API Access Token with limited access to your data warehouse.

  • Visualizing a dataset with deck.gl

  • Publishing your app

During this guide, we're using the CARTO Data Warehouse. The process explained here is also compatible with other Warehouses like BigQuery, Snowflake, Redshift, or Postgres. Instead of using connection=carto_dw, you need to use connection=<your_connection>.

Scaffolding your application

We will use Vite to manage the tooling of our frontend application.

With NPM:

npm create vite@latest

Then you can choose your favorite framework (Vanilla, Vue, React, Preact, etc..) and Typescript or Javascript. In order to make this guide the most compatible as possible, we're going to use Vanilla and for the variant, we're going to select Typescript.

cd <project-name>
npm install 
npm run dev

After that, you should have a project up and running at http://127.0.0.1:5174/

Open the project you've just created in your favorite Code Editor (we recommend Visual Studio Code), and let's do some cleanup in the default template provided by Vite in order to have a full empty space.

  • Remove src/counter.ts file.

  • Replace src/main.ts with the following:

import './style.css'

document.querySelector<HTMLDivElement>('#app')!.innerHTML = ``
  • Replace src/style.css with the following:

body, html {
  height: 100%;
  margin: 0;
  overflow: hidden;
  padding: 0;
  position: fixed;
  width: 100%;
  font-family: Inter, sans-serif;
  font-weight: 400;
  font-size: 1rem;
}
#app {
  flex: 1 1 auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

You will now see a completely empty page. No worries! We're going to start adding content in the following sections.

Adding a Basemap

We're going to include a basemap in your application. As explained in the Basemap section, you can use multiple basemaps (CARTO Basemaps, Google Maps, Amazon Location, etc...). For this guide we'll use the CARTO Basemaps, as they're available to all CARTO organizations, and do not require a third-party service.

First, we're going to install the required dependencies:

npm install maplibre-gl @deck.gl/core @deck.gl/carto

Then, create a file src/map.ts with this content:

import maplibregl from 'maplibre-gl';
import { Deck } from '@deck.gl/core/typed';
import { BASEMAP } from '@deck.gl/carto/typed';

export function createMap() {
  const INITIAL_VIEW_STATE = {
    latitude: 39.8097343,
    longitude: -98.5556199,
    zoom: 4,
    bearing: 0,
    pitch: 30
  };

  const deck = new Deck({
    canvas: 'deck-canvas',
    initialViewState: INITIAL_VIEW_STATE,
    controller: true,
  })

  const map = new maplibregl.Map({container: 'map', style: BASEMAP.VOYAGER, interactive: false});
  deck.setProps({
    onViewStateChange: ({viewState}) => {
      const {longitude, latitude, ...rest} = viewState;
      map.jumpTo({center: [longitude, latitude], ...rest});
    }
  });
}

Next, add this to src/style.css:

#map, canvas{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  max-height: 100%;
}

And replace src/main.ts with this code:

import './style.css'
import 'maplibre-gl/dist/maplibre-gl.css';
import { createMap } from './map'

document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
  <div id="map"></div>
  <canvas id="deck-canvas"></canvas>
`
createMap()

Creating an API Access Token

In order to use the CARTO APIs you need to authenticate your requests. For a public application the recommended approach is do so by creating an API Access Token. This token will be public so you need to guarantee it has limited access to the resources of your public application. You can read more about API Access Tokens here.

In this application, we're going to visualize the table: carto-demo-data.demo_tables.populated_places.To create an API Access Token with access to the previous table, you need to go to CARTO Workspace -> Developers -> Manage API Access Tokens. More info on these steps here.

You should add the previous table as a grant:

We also recommend limiting the token by referers URLs.

The process is exactly the same if you're using another warehouse like BigQuery, Snowflake, Redshift, or PostgreSQL.

This API Access Token is an environment configuration, so let's add it as an environment variable.

Create a file .env in the root folder:

# API Base URL (copy this from CARTO Workspace -> Developers)
VITE_API_BASE_URL=https://gcp-us-east1.api.carto.com

# Set this variable if you're using an API Access Token (public application).
# Go to app.carto.com -> Developers -> Manage API Access Tokens
VITE_API_ACCESS_TOKEN=XXX

If you have a different region, you need to modify VITE_API_BASE_URL.

Visualizing a dataset with deck.gl

Now, we're going to visualize the populated places dataset using deck.gl and CARTO Maps API. In this section, we're going to modify src/map.ts.

Import the requirements from CARTO for deck.gl:

import {
  BASEMAP,
  CartoLayer,
  setDefaultCredentials,
  MAP_TYPES
} from '@deck.gl/carto/typed';

Set the credentials to connect with CARTO:

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL
const accessToken = import.meta.env.VITE_API_ACCESS_TOKEN
setDefaultCredentials({ apiBaseUrl,  accessToken })

Finally, create the layer to visualize both the populated places dataset and pass it to the Deck class:

const deck = new Deck({
  canvas: 'deck-canvas',
  initialViewState: INITIAL_VIEW_STATE,
  controller: true,
  layers: [
    new CartoLayer({
      id: 'places',
      connection: 'carto_dw',
      type: MAP_TYPES.TABLE,
      data: 'carto-demo-data.demo_tables.populated_places',
      pointRadiusMinPixels: 3,
      getFillColor: [200, 0, 80],
    })
  ]
})

Publish your application

Congratulations! You now have a working public application that will display your dataset in a map for any viewer. The application is a static website that can be deployed on your favorite web server.

Using the following command you can generate the necessary static files:

npm run build

Vite also provides a guide to deploy a static website on different platforms like GitHub Pages, GitLab Pages, Netlify, Vercel, Firebase, etc.

What's next?

All the code for this guide is available on GitHub.

git clone https://github.com/CartoDB/carto-for-developers-guides.git
cd carto-for-developers-guides/public-app

We recommend you to visit CARTO + deck.gl to learn more about the different visualizations you can create using deck.gl. There are many examples in our gallery that might be useful to improve your application!

Last updated