How to add Leaflet Map in Ionic -4 or Angular

In most of the apps, maps are one of the most useful tools for users when included in an app. In the last example, I had added Google map in ionic. In this example, we learning how to add Leaflet map in Ionic 4.

The Leaflet is a widely used open-source JavaScript library used to build web mapping applications. it is one of the most popular JavaScript mapping libraries and is used by major websites such as FourSquare, Pinterest, and Flickr.

Step 1: Step up the project

ionic start leafletIonic tabs
npm install leaflet --save

Step 2: Configure Leaflet in project

We have set leaflet in our project, inside angular.json  add the following:

"assets": [
      ...,
      {
        "glob": "**/*",
        "input": "./node_modules/leaflet/dist/images",
        "output": "leaflet/"
      }
    ],
       "styles": [
		....., 
		{
		   "input": "./node_modules/leaflet/dist/leaflet.css"
		}
        ],

Step 2: Set up the Template

We don’t need to test this app on a real device, we can test on the browser. First, we modify the existing code of the tab.html. Replace existing code with the following code in app/tabs/tabs.page.html 

<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="tab1">
      <ion-icon name="flash"></ion-icon>
      <ion-label>Leaflet 1</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2">
      <ion-icon name="apps"></ion-icon>
      <ion-label>Leaflet 1</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3">
      <ion-icon name="send"></ion-icon>
      <ion-label>All Map</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

We will rename the existing page to the new name, in the first two tab page we will display the different location and different design for each page and last page we will displaying multiple markers.

Step 3: Set up First Leaflet design 

Add the following code in src/apps/tab1/tab1.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Leaflet 1
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div id="mapId" style="width: 100%; height: 100%">
  </div>
</ion-content>

Add the following code in apps/tab1/tab1.page.ts

import { Component } from '@angular/core';
import { Map, latLng, tileLayer, Layer, marker } from 'leaflet';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  map: Map;

  ionViewDidEnter() { this.leafletMap(); }

  leafletMap() {
    // In setView add latLng and zoom
    this.map = new Map('mapId').setView([28.644800, 77.216721], 10);
    tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'edupala.com © ionic LeafLet',
    }).addTo(this.map);


    marker([28.6, 77]).addTo(this.map)
      .bindPopup('Ionic 4 <br> Leaflet.')
      .openPopup();
  }

  /** Remove map when we have multiple map object */
  ionViewWillLeave() {
    this.map.remove();
  }
}

Step 4: Set up Second Leaflet design 




Add the following code in apps/tab2/tab2.page.html, we need to add different id for div containing a map, as ionic and angular are single page application.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Tab Two
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div id="mapId2" style="width: 100%; height: 100%"></div>
</ion-content>

Add the following code in apps/tab2/tab2.page.html

import { Component } from '@angular/core';
import { Map, tileLayer, marker } from 'leaflet';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
  map: Map;

  ionViewDidEnter() {
    this.leafletMap();
  }

  leafletMap() {
    this.map = new Map('mapId2').setView([12.972442, 77.594563], 13);

    tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      attribution: 'edupala.com'
    }).addTo(this.map);

    const markPoint = marker([12.972442, 77.594563]);
    markPoint.bindPopup('<p>Tashi Delek - Bangalore.</p>');
    this.map.addLayer(markPoint);
  }

  ionViewWillLeave() {
    this.map.remove();
  }

}

Step 5: Adding multiple markers in Leaflet Map

In tab1 and tab2 we display leaflet map with single maker. In tab3 we will add multiple leaflet marker in the Leaflet map.

Add following data on data.JSON in www/assets/data.json as

 {
    "properties" : [
    {,
        "city": "Cambridge",
        "state" : "MA",
        "long": -71.10858,
        "lat": 42.35963
    },
    {
        "city": "Cambridge",
        "state": "MA",
        "long": -71.10869,
        "lat": 42.359103,
    },
    {
        "city": "Boston",
        "state": "MA",
        "long": -71.110061,
        "lat": 42.360686,
    },
    {
        "city": "Cambridge",
        "long": -71.110448,
        "lat": 42.360642
    }
    ]
 }

Add the following code in apps/tab3/tab3.page.ts

import { Component } from '@angular/core';
import { Map, tileLayer, marker } from 'leaflet';
@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {
  map: Map;
  propertyList = [];

  constructor() { }

  ionViewDidEnter() {
    this.map = new Map('mapId3').setView([42.35663, -71.1109], 16);

    tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      attribution: 'edupala.com'
    }).addTo(this.map);

    fetch('./assets/data.json').then(res => res.json())
    .then(json => {
      this.propertyList = json.properties;
      this.leafletMap();
    });
  }

  leafletMap() {
    for (const property of this.propertyList) {
      marker([property.lat, property.long]).addTo(this.map)
        .bindPopup(property.city)
        .openPopup();
    }
  }

  ionViewWillLeave() {
    this.map.remove();
  }
}

Add the following code in apps/tab3/tab3.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Leaflet All Property
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div id="mapId3" style="width: 100%; height: 100%"></div>
</ion-content>