deleting the existing marker before placing a new marker on the Mapbox

Upon the map loading with GeoJson data, I have implemented code to display markers at specified locations. It works flawlessly, but I am seeking a way to remove previous markers when new ones are added. What adjustments should be made for this desired functionality?

Below is the complete function:

prepareGeoJsonData(data) {
    let features = [];
    let counter = 0;

    for (let val of data) {
      features.push({
        type: "Feature",
        geometry: val.address.geometry.border,
        center: val.address.geometry.center,
        properties: {
          center: val.address.geometry.center.coordinates,
          landUnitId: val.memberOf.parcel[0]
        },
        id: counter++,
      });
      //
code for marker customization
//
        let marker = new mapboxgl.Marker(el)
          .setLngLat(cords)
          // .setPopup(popup)
          .addTo(this._mapRef);
        this.markers.push(marker);
      }
    };
    return {
      type: "FeatureCollection",
      features: features
    };
  }

Current Flow:

Page Loads -> Map Loads -> Markers Appear -> Apply filters -> New Markers Added -> Previous Markers Still Present

Required Flow:

Page Loads -> Map Loads -> Markers Appear -> Apply filters -> New Markers Added -> Previous Markers Disappear

Answer №2

I encountered a similar issue and after conducting some research, I was unable to locate a solution. Mapbox does offer a marker.remove() method that can be utilized. Here is the approach I took:

                                      // Handling map data on click event
                                      var clickMark = mapInner.on('click', (e) => {
                                        var coordinates = e.lngLat;
                                        
                                        // Creating a new marker.
                                        var marker = new mapboxgl.Marker()
                                        .setLngLat(coordinates)
                                        .addTo(mapInner);

                                       // Internal click event to remove previous marker
                                        mapInner.on('click', () => {
                                          try {
                                            marker.remove();
                                          }
                                          catch(err) {
                                            console.log(err)
                                          }
                                        });
                                        
                                        });

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

Is there a way to simulate the BeforeInstallPromptEvent for testing in Jasmine/Angular?

I'm currently working on testing a dialog component that manages the PWA install event triggered manually when a specific function is invoked. The goal is to handle the promise returned by the BeforeInstallPromptEvent.userChoice property. However, wh ...

Extract data from Angular2 class

I am having trouble with the data binding of {{value}}. Here is a straightforward example: app.component.ts import {Component, OnInit} from "@angular/core"; @Component({ selector: "app", templateUrl: "./app/app.html" }) ...

Establish a connection between two JSON files using the WordPress REST API

I have developed an app using ionic 2 that revolves around quotes. My goal is to manage these quotes (along with authors, categories, etc) using Wordpress and its REST API. Initially, I utilized normal posts for this purpose, but now I am exploring custom ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Steps for importing jQuery to vendor.ts in Angular 2 webpack

Currently, I am in the process of setting up my Angular 2 app using webpack. As I review the vendor.ts file, I notice this specific structure. // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; ...

Maintaining search filters across pages in Angular 2 using URL parameters

I am attempting to store certain filters in the URL for my application, so that they can be reapplied when the page is reloaded. I am encountering challenges with Dates (using moment), nullable properties, and special characters (/). When I pass values to ...

Service in Angular - Triggering a signal with an HTTP request

I have created a service with the following structure: const initialState: IUserState | null = null @Injectable({ providedIn: 'root' }) export class AuthService { private user = signal(initialState) constructor (private http: HttpClient) { ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

Setting up Apache to work with Angular 2

I am in the process of setting up a virtual host for my Angular2 application. I found an article that seems helpful: https://www.packtpub.com/mapt/book/Web+Development/9781783983582/2/ch02lvl1sec15/Configuring+Apache+for+Angular The instructions suggest ...

Unable to allocate information in the subscribe method

I'm experiencing an issue with the post method. Whenever I try to retrieve data using the segmentService, I always receive an empty segmentdata object in my temporarySegment variable. Strangely enough, when I use the same approach for retrieving numbe ...

Utilize localStorage.getItem() in conjunction with TypeScript to retrieve stored data

Within my codebase, I have the following line: const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal; Unexpectedly, Typescript triggers an alert with this message: Argument ...

Troubleshooting column alignment with Bootstrap4 and Angular: Resolving issues with text alignment on

Being relatively new to Bootstrap 4, as I have only used version 3.3 on my previous project which did not utilize the flexbox grid system. Now that I am embarking on a new project, I find myself facing a challenge: I am struggling to apply the "text-alig ...

The wss websocket connection is experiencing issues in Firefox 89 when attempting to connect on localhost

For some reason, the websocket wss connection is not working in Firefox 89 when trying to connect on localhost. Interestingly, I can successfully establish a connection using my to connect to from the production server. However, when attempting to init ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Guide to creating content on an NFC tag with Ionic

I am struggling with my button calling the test2 function and the code I have is not working as expected. Here is what I currently have: import { Component } from '@angular/core'; import { NFC, Ndef } from '@ionic-native/nfc/ngx'; @Com ...

Angular 8 UI not displaying mockAPI data as expected

My mockAPI is successfully fetching the data, but the json response structure is quite complex. It looks something like this: [ { "planList": [ // plan details here ] } ] Everything in the UI is displaying correctly, except ...

Encountering a unique webpack error while attempting to upgrade Angular from version 11 to version

Struggling to upgrade my Angular version from 11.1.1 to 12.1.1 and encountering a build error. "CustomWebpackDevServerSchema" schema is using the keyword "id" which its support is deprecated. Use "$id" for schema ID. "BuildCustomWebpackBrowserSchema" sche ...

Learn the steps to establish a one-to-many relational record with the help of Node.js and Sequelize-Typescript

Currently, I am working on Nodejs with sequelize-typescript to develop a CRUD system for a one-to-many relationship. Unfortunately, I have encountered an issue with my code that I cannot seem to pinpoint. While I am able to retrieve records successfully us ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...