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

Troubleshooting the Ui-router refresh problem

I set up my ui-router configuration as follows: app.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: "/home", templateUrl : 'h ...

The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow: UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.n ...

What is the best way to provide inputs to a personalized validation function?

I am seeking a solution to pass an array of prefix strings to my custom validator in order to validate that the value begins with one of the specified prefixes. Below is the code snippet for my current validator: @ValidatorConstraint({ name: 'prefixVa ...

Angular2 tutorial with VS2015 may encounter a call-signature error that is expected

Currently following the Angular2 tutorial in VS2015 and encountering an issue with a warning that is impeding the compilation of one of my TypeScript files. The link to the tutorial is provided below. https://angular.io/docs/ts/latest/tutorial/toh-pt4.htm ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

What is the process for setting up a subrouter using React Router v6?

This is the current React Router setup I am using: const router = createBrowserRouter([ { path: "/", element: ( <Page activeNav="home" > <Home /> </Page> ) }, { ...

One approach to enhance a function in Typescript involves encapsulating it within another function, while preserving

What I Desire? I aim to create a function called wrap() that will have the following functionality: const func = (x: string) => 'some string'; interface CustomObject { id: number; title: string; } const wrapped = wrap<CustomObject> ...

Updating Values in Nested Forms with Angular Reactive Form

I have been grappling with a form setup that looks something like this: itemEntities: [ {customisable: [{food: {..}, quantity: 1}, {food: {..}, quantity: 5}]}, {customisable: [{food: {..}, quantity: 0}]}, ] My challenge lies in trying to u ...

Having trouble with Angular and PrimeNG: CSS styling not rendering

I recently started using PrimeNG but I'm having trouble getting the styles to look good. Despite not seeing any errors in ng serve or the browser logs, the components (a calendar and 3 buttons) appear dull. app.module.ts import { BrowserModule } fro ...

Using TypeScript to style React components with the latest version of Material UI, version

Styled typography component accepts all the default typography props. When I include <ExtraProps> between styled() and the style, it also allows for extra props. const StyledTypography = styled(Typography)<ExtraProps>({}) My query is: when I r ...

What is the best way to delete markers from a leaflet map?

I need to remove markers from my map. I am looking to create a function that will specifically clear a marker based on its ID. I am utilizing Leaflet for the map implementation. Here is my function: public clearMarkers(): void { for (var id in this. ...

Challenges of implementing dark mode with a checkbox and local storage

I'm experiencing an issue with local storage. When I enable the dark mode, everything functions properly and the local storage 'dark' is set to true. However, upon refreshing the page, the local storage remains true but the toggle switches b ...

What is the best way to remove a specific row from an Angular Material table that does not have any filters

Here is my samplepage.component.ts code: import { Component } from '@angular/core'; @Component({ selector: 'app-batchticketvalidation', templateUrl: './batchticketvalidation.component.html', styleUrls: ['./batchtic ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

What is the process for incorporating a new index signature into a class declaration from a file.d.ts in typescript?

I am facing an issue with a class in my project: // some npm module export class User { fname: string; lname: string; } Unfortunately, I cannot modify the declaration of this class from my project root since it is an npm module. I wish to add a new in ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Working with Angular: Managing an Array of Objects

After retrieving an array of objects using the code snippet below: this.serviceOne.getRemoteData().subscribe( data => this.MyArray.push(data) ); I encounter issues when trying to iterate through the array using the code snippet bel ...

Unexpected silence from the Express web server

I am currently in the process of setting up my Angular application for Server Side Rendering using Angular Universal. Below is the JS file that has been generated by Angular Universal, with minor modifications made to the path and port: import 'zone ...

The NestJS Backend is always being asked by Grafana to access the /api/live/ws endpoint

After successfully setting up Grafana and Grafana Loki with my NestJS Backend, everything seemed to be working fine. However, I started getting a 404 error from my NestJS because Grafana was requesting the /api/live/ws route. Is there a way to disable thi ...