Using Mapbox in Angular application

Showing a simple map

Timo Bähr
Jun 19 · 2 min read

This tutorial explains how to show a simple map inside an existing Angular application using the Mapbox SDK. We do not explain how to show markers or anything else.

Expected result of this tutorial

Integration steps

Go to Mapbox, make an account and fetch your Mapbox token.

npm install mapbox-gl --save
npm install @types/mapbox-gl --save
<script src='https://api.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.css' rel='stylesheet' />
export const environment = {
...

mapbox: {
accessToken: 'YOUR_TOKEN'
}
}

Create a component that is responsible for showing the map. Using Angular CLI this is a one liner.

ng g component map

map.component.css contains style match-parent, that makes the map as large as possible inside the parent view:

.match-parent {
width: 100%;
height: 100%;
}

map.component.html is simply a div container:

<div class="map" id="map" class="match-parent"></div>

map.component.html is simply a div container:

<div class="map" id="map" class="match-parent"></div>

map.component.ts imports mapboxgl and injects the map into the empty div container at initialization:

import { environment } from '../../../environments/environment';
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import * as mapboxgl from 'mapbox-gl';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
map: mapboxgl.Map;
style = 'mapbox://styles/mapbox/streets-v11';
lat = 37.75;
lng = -122.41;
constructor() { } ngOnInit() {
mapboxgl.accessToken = environment.mapbox.accessToken;
this.map = new mapboxgl.Map({
container: 'map',
style: this.style,
zoom: 13,
center: [this.lng, this.lat]
});
// Add map controls
this.map.addControl(new mapboxgl.NavigationControl());
}
}

Common errors

Check if your parent view does have width and height bigger 0.