How to add Leaflet Map in Ionic -3

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 3.

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: Set up the Tabs Template

We don’t need to test this app on 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 pages/tabs/tabs.html

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Leaflet 1" tabIcon="locate"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Leaflet 2" tabIcon="locate"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="All Map" tabIcon="map"></ion-tab>
</ion-tabs>

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

Modify the tabs.ts file

import { Component } from '@angular/core';
import { LeafletPage } from '../leaflet/leaflet';
import { Leaflet2Page } from '../leaflet2/leaflet2';
import { AllMapPage } from '../allMap/allMap';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {

  tab1Root = LeafletPage;
  tab2Root = Leaflet2Page;
  tab3Root = AllMapPage;

  constructor() {}
}

Step 3: Set up First Leaflet design 

Add the following code in src/pages/leaflet/leaflet.html

<ion-header>
  <ion-navbar color="primary">
    <ion-title>Leaflet Map Design 1</ion-title>
  </ion-navbar>
</ion-header>

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

Add the following code in src/pages/leaflet/leaflet.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import L from "leaflet";

@Component({
  selector: 'page-leaflet',
  templateUrl: 'leaflet.html'
})
export class LeafletPage {
  map: L.Map;
  center: L.PointTuple;

  constructor(public navCtrl: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad MapPage');
    this.center = [28.644800, 77.216721];
    this.leafletMap();
  }

  leafletMap(){
    this.map = L.map('mapId', {
      center: this.center,
      zoom: 13
    });

    var position = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'edupala.com © ionic LeafLet'
    }).addTo(this.map);

    var marker = new L.Marker(this.center);
    this.map.addLayer(marker);

    marker.bindPopup("<p>Tashi Delek.<p>Delhi</p>");
  }
}

Add the following code in leaflet.scss

page-leaflet {
    .map-container {
        position: absolute;
        top: 0px;
        bottom: 0px;
        width: 100%;
        height: 100%;
    }
}

 

Step 4: Set up Second Leaflet design 




Add the following code in src/pages/leaflet2/leaflet2.html


<ion-header>
  <ion-navbar color="primary">
    <ion-title>Leaflet Design 2</ion-title>
  </ion-navbar>
</ion-header>

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

Add the following code in src/pages/leaflet2/leaflet2.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import L from "leaflet";

@Component({
  selector: 'page-leaflet2',
  templateUrl: 'leaflet2.html'
})
export class Leaflet2Page {
  map: L.Map;
  center: L.PointTuple;

  constructor(public navCtrl: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad MapPage');
    this.center = [12.972442, 77.594563];
    this.leafletMap();
   
  }

  leafletMap(){
    this.map = L.map('mapId2', {
      center: this.center,
      zoom: 13
    });

    var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="http://cartodb.com/attributions">CartoDB</a>'
    }).addTo(this.map);

    var marker = new L.Marker(this.center);
    this.map.addLayer(marker);

    marker.bindPopup("<p>Tashi Delek - Nmasta Bangalore.</p>");
   }
 }

Add the following code in leaflet2.scss

page-leaflet2 {
    .container-map {
        position: absolute;
        top: 0px;
        bottom: 0px;
        width: 100%;
        height: 100%;
    }
}

 

Step 5: Adding multiple markers in Leaflet Map

We have created three-page in this apps, two to display the list of the single leaflet map. This page we will add multiple leaflet marker in the Leaflet map.

 

Add following data on data.JSON in www/assets/data/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 src/pages/allMap/allMap.html

<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Ionic Leaflet All Multiple Marker
    </ion-title>
  </ion-navbar>
</ion-header>

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

 

Add the following code in src/pages/allMap/allMap.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Http } from '@angular/http';
import 'rxjs/add/operator/map';
import L from "leaflet";

@Component({
  selector: 'page-allMap',
  templateUrl: 'allMap.html'
})
export class AllMapPage {
  propertyList = [];
  center: L.PointTuple;
  map;

  constructor(public navCtrl: NavController, private http: Http) {
    this.http.get('assets/data/data.json')
    .map(res => res.json())
    .subscribe(data => {
        this.propertyList = data.properties;
    },
    err => console.log("error is "+err), // error
      () => this.leafletMap()
    );
  }

  ionViewDidLoad() {
    this.map = L.map('mapId').setView([42.35663, -71.1109], 16);
    
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);
  }


  leafletMap(){
    console.log("property" + this.propertyList.length);
    for (let property of this.propertyList) {
      L.marker([property.lat, property.long]).addTo(this.map)
      .bindPopup(property.city)
      .openPopup();
    }
  }
}