Integrating Mapbox with Angular (Part 1: Setup with TypeScript Support)

Integrating maps and adding interactivity to them can be a bit tricky at first. In this post, I’ll show you how to easily add a basic map using Mapbox in your Angular project.

Mapbox offers several ways to use their maps, but the most straightforward approach is through their official npm package: mapbox-gl.

Step 1: Install the Mapbox GL JS package

npm i --save mapbox-gl

Step 2: Include the Mapbox CSS in index.html
In your index.html file, inside the

tag, add the following:

<link href='https://api.mapbox.com/mapbox-gl-js/v3.13.0/mapbox-gl.css' rel='stylesheet' />

Don’t just copy-paste, always check Mapbox’s official docs for the latest version.

Step 3: Get Your Mapbox Access Token
Log into your Mapbox account and generate a public access token (pk.).
If you’re using Mapbox on a frontend-only app, a public token is enough.
For backend services, use a secret token (sk.), but never expose it in frontend code.

Step 4: Create Map Component
map.ts

import { AfterViewInit, Component } from '@angular/core';
import mapboxgl, { Map } from 'mapbox-gl';

@Component({
  selector: 'app-map',
  templateUrl: 'map.html',
  styleUrls: ['map.css']
})
export class MapComponent implements AfterViewInit {
map!: Map;
accessToken = ''; // Add your public token here
mapStyle = 'mapbox://styles/mapbox/streets-v12'

ngAfterViewInit(): void {
    mapboxgl.accessToken = this.accessToken;
    this.map = new mapboxgl.Map({
      container: 'map', // matches the div ID
      style: this.mapStyle,
      center: [20, 50], // [lng, lat]
      zoom: 3,
    });
  }
}

map.html

<div id="map"></div>

map.css

#map {
  width: 100%;
  height: 100%;
}

Important:
Make sure that the parent element of your map (and the map container itself) has a defined width and height.
If either of them is missing, Mapbox won’t know how big the map should be, and you might just see a blank box.

Example fix:
map.css

.map-section {
  width: 100vw;
  height: 100vh;
}

#map {
  width: 100%;
  height: 100%;
}

map.html

<section class="map-section">
  <div id="map"></div>
</section>

If your map still overflows or causes scrollbars, make sure you reset global margins and paddings:

styles.css

html,
body {
  margin: 0;
  padding: 0;
}

This is the most basic way to include Mapbox in your project.
In upcoming posts, I’ll show you how to make your map more interactive using real-world data.