Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to add Angular leaflet Map in Angular?

Angular leaflet map example

In many applications, maps are one of the most useful tools to interact with users. In this tutorial, we’ll learn and demonstrate an example to add an Angular leaflet map. 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.

Prerequisites:
Only for if you have not yet installed Angular and Node js. To create and run an Angular project, We need Node js and Angular CLI already install in our system, if not then check how to install node js and angular in Ubuntu. Angular CLI allows us to create an Angular project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install latest the Angular CLI, open a terminal and run the following command:

npm install -g @angular/cli

Setting up a project for Angular leaflet map example?

Let’s create a project to demonstrate an example of how to add a leaflet map in the angular 10 projects. We need to install our leaflet and leaflet-ant-path library in our project. Angular leaflet ant-path will display the path by latitude and longitude which we set.

ng new leafletMapApps
npm install leaflet --save
npm install leaflet-ant-path --save

Let’s add two angular components, one for the Angular leaflet ant-path example and other components for adding multiple leaflet markers.

ng g component leaftlet-path
ng g component leaflet-makers

Import style of Angular leaflet map in angular project

For the map to render correctly, we need to import the Leaflet stylesheet to the Angular project. To do this import leaflet style in styles.scss as

@import "~leaflet/dist/leaflet.css"

In our app.component.html file, we have two buttons for routing between our two components. Edit app.component.html file.

<div>
  <button mat-button color="success" routerLink="/leaflet-path">Leaflet ant-path</button>
  <button mat-button color="success" routerLink="/leaflet-multiple-marker">Multiple marker</button>
</div>
<router-outlet></router-outlet>

Edit app-routing.module.ts to include routing between our components.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LeafletMakersComponent } from './leaflet-makers/leaflet-makers.component';
import { LeaftletPathComponent } from './leaftlet-path/leaftlet-path.component';

const routes: Routes = [
  { path: 'leaflet-multiple-marker', component: LeafletMakersComponent },
  { path: 'leaflet-path', component: LeaftletPathComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Example of Angular leaflet with ant-path

In our, the leaflet-path.component.html, add div with map id, map div, and set style width and height for a map div element. This div element is the place where we render our leaflet map. We will add a map from our component typescript file.

Angular leaflet map example

Edit leaflet-path.component.html and

Edit leaftlet-path.component.html and leaftlet-path.component.scss

<h2 style="text-align: center;"> Demo 1: Angular Leaflet with ant-path</h2>
<div id="map"></div>
#map {
  width: 100%;
  height: 600px;
}
import { Component, OnDestroy, OnInit } from '@angular/core';
import * as Leaflet from 'leaflet';
import { antPath } from 'leaflet-ant-path';

@Component({
  selector: 'app-leaftlet-path',
  templateUrl: './leaftlet-path.component.html',
  styleUrls: ['./leaftlet-path.component.scss']
})
export class LeaftletPathComponent implements OnInit, OnDestroy {
  title = 'leafletApps';
  map: Leaflet.Map;

  ngOnInit(): void {
    this.map = Leaflet.map('map').setView([28.644800, 77.216721], 5);
    Leaflet.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'edupala.com © Angular LeafLet',
    }).addTo(this.map);

    Leaflet.marker([28.6, 77]).addTo(this.map).bindPopup('Delhi').openPopup();
    Leaflet.marker([34, 77]).addTo(this.map).bindPopup('Leh').openPopup();

    antPath([[28.644800, 77.216721], [34.1526, 77.5771]],
      { color: '#FF0000', weight: 5, opacity: 0.6 })
      .addTo(this.map);
  }

  ngOnDestroy(): void {
    this.map.remove();
  }

}

In the ngOnInit() method in our component, we pass the div id of our map, which we name as a map. In our example, we want to center our map on Delhi the capital of India and located at 28.644800 latitudes and longitude 77.216721.

The leaflet maker method allows us to add marker icons, we have added two markers one at Delhi and the other in Ladakh.

We have leaflet ant paths, which allows us to draw an animated path between two different places in our leaflet map. We have drawn an animated path from Delhi to Ladakh by supplying the latitude and longitude of two places in leaflet-ant-path.

Example 2 of Angular leaflet with multiple marker

Our previous example is an Angular leaflet with a single marker, and the leaflet allows us to add multiple markers to our map. Let’s create dummy data for multiple makers to indicate a different property of the real estate company. Add folder data in assets/data and create folder data.json and add the following data with latitude and longitude of properties.

angular leaflet with multiple marker
{
    "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
        }
    ]
}

Edit our component leaflet-makers.component.html to include div with map id for our Angular leaflet map.

<h2 style="text-align: center;"> Demo 2 : Leaflet multiple marker on all Property</h2>
<div id="mapId2" style="width: 100%; height: 100%"></div>

Edit leaflet-maker typescript file to fetch our data for leaflet multiple markers and create a leaflet map.

import { Component, OnDestroy, OnInit } from '@angular/core';
import * as Leaflet from 'leaflet';

@Component({
  selector: 'app-leaflet-makers',
  templateUrl: './leaflet-makers.component.html',
  styleUrls: ['./leaflet-makers.component.scss']
})
export class LeafletMakersComponent implements OnInit, OnDestroy {
  map: Leaflet.Map;
  propertyList = [];

  constructor() { }

  ngOnInit(): void {
    this.map = new Leaflet.Map('mapId2').setView([42.35663, -71.1109], 16);

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

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

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

  ngOnDestroy(): void {
    this.map.remove();
  }

}

Conclusion
In this tutorial, we have completed an example of an Angular leaflet map and added an ant-path of the leaflet in our angular project. There are many open-source javascript libraries to include maps in our project. The Leaflet holds the leading position among open-source JavaScript libraries for interactive maps. Check our full code of the angular leaflet map in the GitHub repository.

Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021

Related posts

How to add Angular leaflet Map in Angular?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top