Adding the Map Leaflet component to an Angular application

Angular is a development platform for building web, mobile, and desktop applications using HTML, CSS, and TypeScript (JavaScript). Currently, Angular is at version 13, and Google is the main maintainer of the project.

Leaflet is an interactive map component library that supports mobile devices.

Before you begin, you need to install and configure the tools:

Create and configure the account on the Mapbox

1. Let’s create the account. Go to and click the button Register.

2. Fill in the fields username, E-mail, Password, First name, Last nameclick on the checkbox I agree to the Mapbox Terms of Service and Privacy Policy and click the button To start.


3. Check the registered email.


4. Click on the link in the email sent.


5. Copy the token displayed in the Dashboard menu and in my case the token was displayed pk.eyJ1IjoiYnJhc2thbSIsImEiOiJja3NqcXBzbWoyZ3ZvMm5ybzA4N2dzaDR6In0.RUAYJFnNgOnnZAw because this token will be configured in the Angular application.


6. Ready! Account created and token generated.

Create the Angular app

1. Now let’s create the application with the Angular base framework using the @angular/cli with route file and SCSS style format.

ng new angular-leaflet
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [                ]
CREATE angular-leaflet/ (1060 bytes)
CREATE angular-leaflet/.editorconfig (274 bytes)
CREATE angular-leaflet/.gitignore (604 bytes)
CREATE angular-leaflet/angular.json (3261 bytes)
CREATE angular-leaflet/package.json (1077 bytes)
CREATE angular-leaflet/tsconfig.json (783 bytes)
CREATE angular-leaflet/.browserslistrc (703 bytes)
CREATE angular-leaflet/karma.conf.js (1432 bytes)
CREATE angular-leaflet/ (287 bytes)
CREATE angular-leaflet/tsconfig.spec.json (333 bytes)
CREATE angular-leaflet/src/favicon.ico (948 bytes)
CREATE angular-leaflet/src/index.html (300 bytes)
CREATE angular-leaflet/src/main.ts (372 bytes)
CREATE angular-leaflet/src/polyfills.ts (2820 bytes)
CREATE angular-leaflet/src/styles.scss (80 bytes)
CREATE angular-leaflet/src/test.ts (788 bytes)
CREATE angular-leaflet/src/assets/.gitkeep (0 bytes)
CREATE angular-leaflet/src/environments/ (51 bytes)
CREATE angular-leaflet/src/environments/environment.ts (658 bytes)
CREATE angular-leaflet/src/app/app-routing.module.ts (245 bytes)
CREATE angular-leaflet/src/app/app.module.ts (393 bytes)
CREATE angular-leaflet/src/app/app.component.scss (0 bytes)
CREATE angular-leaflet/src/app/app.component.html (24617 bytes)
CREATE angular-leaflet/src/app/app.component.spec.ts (1100 bytes)
CREATE angular-leaflet/src/app/app.component.ts (220 bytes)
✔ Packages installed successfully.

2. Install and configure the CSS Bootstrap framework. Complete Steps 2 and 3 of Publishing Add Bootstrap CSS Framework to an Angular Application.

3. Configure the Mapbox token in the src/environments/environment.ts and src/environments/ files as below.

mapbox: {
  accessToken: 'pk.eyJ1IjoiYnJhc2thbSIsImEiOiJja3NqcXBzbWoyZ3ZvMm5ybzA4N2dzaDR6In0.RUAYJFnNgOnn80wXkrV9ZA',

4. Create the src/assets/images folder and copy it marker-icon.png and marker-shadow.png files.


5. Install it leaflet and @types/leaflet libraries.

npm install leaflet @types/leaflet

6. Configure it leaflet library. Change the angular.json file and add the leaflet.css file as below.

"styles": [

seven. Delete the contents of AppComponent class of the src/app/app.component.ts to file. Import it leaflet service and create the getCurrentPosition, loadMap methods as shown below.

import { AfterViewInit, Component } from '@angular/core';
import { Observable, Subscriber } from 'rxjs';
import * as L from 'leaflet';

import { environment } from '../environments/environment';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
export class AppComponent implements AfterViewInit {

  map: any;

  constructor() {

  public ngAfterViewInit(): void {

  private getCurrentPosition(): any {
    return new Observable((observer: Subscriber) => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position: any) => {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
      } else {

  private loadMap(): void { ='map').setView([0, 0], 1);
    L.tileLayer('{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
      attribution: 'Map data © OpenStreetMap contributors, Imagery © Mapbox',
      maxZoom: 18,
      id: 'mapbox/streets-v11',
      tileSize: 512,
      zoomOffset: -1,
      accessToken: environment.mapbox.accessToken,

    .subscribe((position: any) => {[position.latitude, position.longitude], 13);

      const icon = L.icon({
        iconUrl: 'assets/images/marker-icon.png',
        shadowUrl: 'assets/images/marker-shadow.png',
        popupAnchor: [13, 0],

      const marker = L.marker([position.latitude, position.longitude], { icon }).bindPopup('Angular Leaflet');


8. Delete the contents of src/app/app.component.html to file. Add map div tag as shown below.

Angular Leaflet

9. Add the style in the src/app/app.component.scss file as shown below.

#map {
  height: 400px;
  width: 100%;
  max-width: 600px;

ten. Run the application with the command below.

npm start

> [email protected] start
> ng serve

✔ Browser application bundle generation complete.

Initial Chunk Files | Names         |      Size
vendor.js           | vendor        |   2.81 MB
styles.css          | styles        | 280.54 kB
polyfills.js        | polyfills     | 128.51 kB
scripts.js          | scripts       |  76.67 kB
main.js             | main          |  12.03 kB
runtime.js          | runtime       |   6.63 kB

                    | Initial Total |   3.30 MB

Build at: 2021-08-20T10:40:47.188Z - Hash: 030dfe6c9ea7ff5d80c2 - Time: 12256ms

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

✔ Compiled successfully.

11. Ready! Go to url http://localhost:4200/ and check if the app is working. Check that the application works on the GitHub and Stackblitz pages.


The app repository is available at

This tutorial was posted on my blog in Portuguese.

Source link

Comments are closed.