DEV Community

Cover image for Integrating Mapbox with Angular (Part 1: Setup with TypeScript Support)
Đorđe Krstić
Đorđe Krstić

Posted on • Originally published at Medium

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
Enter fullscreen mode Exit fullscreen mode

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' />
Enter fullscreen mode Exit fullscreen mode

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,
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

map.html

<div id="map"></div>
Enter fullscreen mode Exit fullscreen mode

map.css

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

Enter fullscreen mode Exit fullscreen mode

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%;
}
Enter fullscreen mode Exit fullscreen mode

map.html

<section class="map-section">
  <div id="map"></div>
</section>
Enter fullscreen mode Exit fullscreen mode

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

styles.css

html,
body {
  margin: 0;
  padding: 0;
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)