Angular + Leaflet: step by step tutorial to add a map

Angular-based application with a Leaflet map
Angular-based application with a Leaflet map

This tutorial helps you to create an Angular-based application and add a Leaflet map as a component. In our tutorial, we provide a way to use the Leaflet library without additional components. Moreover, we prepared an Angular-project for you that contains already a component skeleton for the map component.

We use Geoapify map tiles for the tutorial. You can choose between different map styles and colors there. Check the Geoapify Maps Playground that contains Live demo and code samples.

We use Mapbox style specification, which describes how the map is rendered, tile server locations, and provides values for map settings. For example, minimum, and maximal zoom levels.

Before you start

Step 1. Create an Angular project

You can use the Angular project template we've prepared for you or create a new one with Angular CLI. The project template contains already a component for a map:

github.com/geoapify/angular-based-project

  • Download or clone the GitHub repository
  • Switch to the project folder: cd angular-based-project
  • Run npm install to install libraries and dependencies
  • Run ng serve for a dev server
  • Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Step 2. Display a map with Leaflet

Install Leaflet + Mapbox GL plugin

By default, Leaflet doesn't support vector tiles and Mapbox Style specifications. Therefore you need to install the Mapbox GL Leaflet plugin together with Leaflet to generate a map from style.json:

npm i leaflet mapbox-gl mapbox-gl-leaflet

Install Leaflet + Mapbox GL types

Type definitions will allow you to utilize Leaflet and Mapbox types in your code. Moreover, some IDEs provide code completion when the types are available:

npm i @types/leaflet @types/mapbox-gl-leaflet -dev

Add Leaflet and Mapbox styles

Leaflet and Mapbox styles are required to render a map and it's elements correctly. We recommend you to add styles to the angular.json:

"projects": {
    "angular-project": {
      ...
      "architect": {
        "build": {
          "options": {
            ...
            "styles": [
              "src/styles.scss",
              "node_modules/mapbox-gl/dist/mapbox-gl.css",
              "node_modules/leaflet/dist/leaflet.css"
            ],
            "scripts": []
          },
          ...
        }
      }
    }
}

You will need to restart the dev server to apply changes from angular.json.

Add a Leaflet map to an Angular-component

Open MyMapComponent if you use our template or create a new component.

  • Remove placeholder and create ViewChild for the div element. Add ngAfterViewInit() lifecycle hook that is called after Angular has fully initialized a component's view:
<div class="map-container" #map></div>
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit, AfterViewInit {

  @ViewChild('map')
  private mapContainer: ElementRef<HTMLElement>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
  }
}
  • Add a Leaflet map to the component:
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import  * as L from 'leaflet';
import 'mapbox-gl-leaflet';

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit, AfterViewInit {

  private map: L.Map;

  @ViewChild('map')
  private mapContainer: ElementRef<HTMLElement>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    const myAPIKey = "YOUR_API_KEY_HERE";
    const mapStyle = "https://maps.geoapify.com/v1/styles/osm-carto/style.json";

    const initialState = {
      lng: 11,
      lat: 49,
      zoom: 4
    };

    const map = new L.Map(this.mapContainer.nativeElement).setView(
      [initialState.lat, initialState.lng],
      initialState.zoom
    );

    // the attribution is required for the Geoapify Free tariff plan
    map.attributionControl
      .setPrefix("")
      .addAttribution(
        'Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | © OpenStreetMap <a href="https://www.openstreetmap.org/copyright" target="_blank">contributors</a>'
      );

    L.mapboxGL({
      style: `${mapStyle}?apiKey=${myAPIKey}`,
      accessToken: "no-token"
    }).addTo(map);
  }
}

Build the application

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

More code samples

Find more Live demos, JSFiddle samples and Code samples on the Geoapify API Documentation page.

World map

Geoapify Location Platform

Choose between different map styles and colors!

Enrich your map with address field, places search, and other location intelligence technics!