Tutorial

How To Build Maps in Angular with Leaflet, Part 3: The Popup Service

Updated on March 29, 2021
author

Chris Engelsma

How To Build Maps in Angular with Leaflet, Part 3: The Popup Service

Introduction

Leaflet supports popups. When clicking on markers or specified regions on the map, popups containing text will appear. This provides a way to display additional information on a map.

Note: This is Part 3 of a 4-part series on using Angular and Leaflet.

In this tutorial, you will learn how to add popups to your map using a service to manage the popup logic.

Prerequisites

To complete this tutorial, you will need:

  • This tutorial builds directly upon the installation and steps in previous parts.

Step 1 — Creating the Popup Service

At this point, you should have a working implementation of Leaflet in an Angular application.

Use your terminal window to navigate to the project directory. Then, run the following command to generate a new service:

  1. npx @angular/cli generate service popup --skip-tests

This will create a new file: popup.service.ts.

Next, you will add this new service as a provider in your app.module.ts.

Open app.module.ts in your code editor and make the following changes:

src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { HttpClientModule } from '@angular/common/http';
import { MarkerService } from './marker.service';
import { PopupService } from './popup.service';

import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';

@NgModule({
  declarations: [
    AppComponent,
    MapComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    MarkerService,
    PopupService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Your application now supports your new PopupService.

Step 2 — Displaying the Popups

Open your newly created popup.service.ts in your code editor. And declare a makeCapitalPopup function:

src/app/popup.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PopUpService {
  constructor() { }

  makeCapitalPopup(data: any): string { }
}

This function will create popups that contain data from the GeoJSON file that was used in Part 2.

Add the capital’s name, state, and population:

src/app/popup.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PopUpService {
  constructor() { }

  makeCapitalPopup(data: any): string {
    return `` +
      `<div>Capital: ${ data.name }</div>` +
      `<div>State: ${ data.state }</div>` +
      `<div>Population: ${ data.population }</div>`
  }
}

Then, you will need to revisit the MarkerService and import the PopupService:

src/app/marker.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as L from 'leaflet';
import { PopupService } from './popup.service';

And inject the PopupService:

src/app/marker.service.ts
constructor(
  private http: HttpClient,
  private popupService: PopupService
) { }

By adding the services to the providers stanza within app.modules.ts, you are creating the services as singleton providers to the entire application, so Angular will not complain about dependency.

While still in the MarkerService file, add the bindPopup() method:

src/app/marker.service.ts
makeCapitalCircleMarkers(map: L.map): void {
  this.http.get(this.capitals).subscribe((res: any) => {
    const maxVal = Math.max(...res.features.map(x => x.properties.population), 0);

    for (const c of res.features) {
      const lat = c.geometry.coordinates[0];
      const lon = c.geometry.coordinates[1];
      const circle = L.circleMarker([lon, lat], {
        radius: MarkerService.ScaledRadius(c.properties.population, maxVal)
      });

      circle.bindPopup(this.popupService.makeCapitalPopup(c.properties));

      circle.addTo(map);
    }
  });
}

Save your changes. Then, stop your application and relaunch it. Open the application in your web browser (localhost:4200) and interact with one of the markers:

Screenshot of a map with a popup displaying information about Austin, Texas.

You now have a map that supports popups.

Conclusion

In this post, you created a popup service that constructs popups. You learned how to attach popups to markers with L.bindPopup.

Continue to Part 4 of this series on using Angular and Leaflet.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Chris Engelsma

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
2 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Hi Chris, thank you for this fantastic guide. There are two little mistakes in your code.

makeCapitalPopup(data: any): string { return `` + <div>Capital: ${ data.name }</div> + <div>State: ${ data.state }</div><^><^> + <div>Population: ${ data.population }</div> }

circle.bindPopup(this.popupService.makeCapitalPopup(c.population));

keep up the great work!

Hi. Thanks for this tutorial. How do we fetch the map markers geojson from the API? Can you please add a code snippet and guide us on that?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more