Using Angular filter pipe to customize markers in Leaflet maps

I am currently working on a select element called district, which lists all the districts in the city.

My objective is to apply a filter that will dynamically display only the leaflet markers corresponding to the selected district on the map. Any suggestions on how I can achieve this?

The code snippet below showcases my map component, illustrating how data is fetched and markers are generated:

refresh() {
    this.artworkService.retrieveAll().then( (artworkList) => {
      this.artworkList = artworkList;
      for (const artwork of this.artworkList) {
        const popupOptions = { className: 'customPopup' };
        const popupInfo =
          "<span class='customPopup'><b>" +
          artwork.name +
          "</b></span>" +
          "<br/>" +
          artwork.firstname + " " + artwork.lastname +
          "<br/>" +
          artwork.streetname + artwork.streetnumber + ", " + artwork.zipcode;
        console.log(artwork.name);
        L.marker([artwork.latitude, artwork.longitude], this.markerIcon)
          .addTo(this.map)
          .bindPopup(popupInfo, popupOptions);
      }

    });

  }

This is the HTML snippet for the filter functionality:

<div class="leaflet-top leaflet-left">
  <div class="filterButton leaflet-control">
    <i class="fa fa-filter fa-7x"></i>
    <strong class="mt-4">District</strong>
    <select class="ml-1" name="zipcode" [(ngModel)]="zipcode">
      <option>-All-</option>
      <option *ngFor="let zipcode of artworkList">{{zipcode}}</option>
    </select>
  </div>
</div>

Answer №1

One way to tackle this could involve using a pipe, but here's an alternative approach to address your problem. This method involves clearing all markers and adding only the necessary ones when you change the value of the select option:

template:

<select
  class="ml-1"
  name="zipcode"
  [(ngModel)]="zipcode"
  (ngModelChange)="changeZipcode()"
>
  <option>-All-</option>
  <option *ngFor="let list of artworkList">{{list.zipcode}}</option>
</select>

ts:

map;
artworkList;
zipcode;
popupOptions = {
  className: "test test2"
};

buildMarkers(artworkList) {
   for (let artwork of artworkList) {
       this.buildPopup(artwork);
   }
}

buildPopup(object) {
    const popupInfo = `
        ${object.name} <br/>
        ${object.firstname}
        ${object.lastname} <br/>
        ${object.streetname} ${object.streetnumber}
        , ${object.zipcode}
      `;
    L.marker([object.latitude, object.longitude], this.markerIcon)
      .addTo(this.map)
      .bindPopup(popupInfo, this.popupOptions);
}

changeZipcode() {
    // clear map of any existing markers
    this.map.eachLayer(layer => {
      if (layer instanceof L.Marker) this.map.removeLayer(layer);
    });
    if (this.zipcode === "-All-") {
      // rebuild all markers as before selection
      this.buildMarkers(this.artworkList);
    } else {
      // filter objects by specific zipcode
      const currentArtworklist = this.artworkList.filter(
        list => list.zipcode == this.zipcode
      );
      this.buildMarkers(currentArtworklist);
    }
}

See full demo here!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Securing Angular2 Routes with Role-Based Authentication

I am striving to develop an AuthGuard function that verifies a user's access to a specific route based on their role and the requested route. If the user has the appropriate role for the route, they should be allowed to proceed; otherwise, they should ...

Ways to increase the size of a div to match the maximum height of its parent container

My current project involves using an angular dialog layout where the API to open and manage the dialog comes from a separate library. The dialog's parent container has a max-height attribute, meaning the dialog's height is determined by its conte ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

How to display a PDF in Angular 6 using a byte array retrieved from a WebAPI

Having trouble opening a PDF from byte array sent by WebAPI. This is my Service: fetchPdfDocument(): Observable<any> { return this.httpClient .get(this.configuration.serverUrl + this.configuration.getPdfDoc, { re ...

Tips for implementing a guard feature using a modal window

I am looking to implement a dialog window with yes and no responses when clicking on a router link. If the user selects 'yes', I want to pass through the canActivate guard. The issue arises when returning to the same router with the guard in pla ...

The user interface is not being refreshed in the select box after removing control from the reactive form

Within my project, I am utilizing "@angular/cli": "1.2.6", "@angular/core": "^4.0.0" Objective My goal is to create a dynamic form for a product that includes feature inputs. When the user clicks the "add feature" button, a new feature column with a sel ...

Creating separate template reference variables for items in an *ngFor loop in Angular can be achieved by using the

I have a question about setting template reference variables for buttons with different attributes when rendering them using *ngFor in Angular. Specifically, I want to set the reference variable as #button1, #button2, and so on for each button, but also ne ...

Mapped TypeScript type requiring scalar properties and allowing optional objects

I am in need of a TypeScript generic type that has the capability to alter another type so that all scalar properties (such as strings, numbers, booleans, etc.) remain mandatory, while object types become optional. For instance, given the User type below, ...

Utilizing Angular routing with Module Federation

I am currently involved in a module federation project. mfe1: ParentApp mfe2: childApp1 mfe3: childApp2 mfe4: childApp3(parent of ChildApp1) Each of the child applications, including childApp1, childApp2, and childApp3, have their own routing modules tha ...

The element 'nz-list-item-meta-title' in NG-ZORRO is unrecognized

After installing NG-ZORRO for my project, I decided to start by incorporating their list component. However, I encountered errors with elements such as: 'nz-list-item-meta-title' and 'nz-list-item-action' not being recognized. I have e ...

The autocomplete suggestions appear as faded gray text following the cursor in the input field, rather than displaying as a pop-up selection

My website is built using Angular 10 and Angular Material. I am looking to enhance the input suggestions in matInput, but in a unique way that differs from matAutocomplete. Instead of displaying a list of options, I want to show just one suggestion for a ...

Warning: Ionic 4 has encountered error code ITMS-90809, indicating the use of deprecated API. Apple has announced they will no longer accept app submissions that utilize

Greetings from the Apple team, It has come to our attention that there are certain issues with your recent app delivery for "Project 66" version 0.0.9. Your delivery was successful, however, we advise you to address the following problem in your upcoming ...

How can I merge these two Observables in Angular to create an array of objects?

Let's say we are working with two different datasets: student$ = from([ {id: 1, name: "Alex"}, {id: 2, name: "Marry"}, ]) address$ = from([ {id: 1, location: "Chicago", sid: 1}, {id: 2, location: &qu ...

Preventing duplicate actions on a Subject with Angular 7's rxjs debounceTime operator

While working on an Angular7 application, I encountered an issue where the KeyUp event of a numeric input was being captured by this specific HTML code: <input fxFlex type="number" formControlName="DM" (keyup)="changeDM()"> </div& ...

What is the best way to transfer PHP form data to an Angular2 application?

As I am still getting familiar with angular2/4, please bear with me if I overlook something obvious. I am currently working on updating a booking process using angular2/4. Initially, the booking procedure commences on a php website, and once some basic in ...

Avoiding redundant code in reactive forms

I have set up reactive forms for both login and registration. Here is the code for the Registration form: <div class="registration_wrap"> <div class="registration"> <form [formGroup]="form" novalidate> < ...

Instructions for utilizing ObjectId with a string _id on the client side

Is there a way to retrieve a document using the _id in string format? Here is an example of the code on the client side: 'use client' ... const Page(){ ... fetch("api/get_data", { method: 'POST', ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

What is the process for incorporating JavaScript files into an Angular project?

I have a template that works perfectly fine on Visual Studio. However, when I try to use it on my Angular project, I encounter an issue with the JavaScript code. I have filled the app.component.html file with the corresponding HTML code and imported the ...

Testing a Mocha import for a class from an unexported namespace

I'm in the process of creating unit tests for my Typescript application using the Mocha test framework. Within my web app, I have an internal module (A) that contains a class B. namespace A { export class B { constructor() { } ...