Angular leaflet markers do not replace each other; they overlap instead

During my ngOnInit initialization process, I set up markers on a map with the same default icon. However, when selecting a marker, I want it to change to a "selected icon". The issue arises when trying to replace the old icon with the new one, as it simply adds the new icon on top of the old one. This results in overlapping icons, making it difficult to clear the selected marker when selecting another one.

vehicleDetails: VehicleDetail[]; //array containing VehicleDetail objects.

markerAdv = Leaflet.Marker.extend({
    options: {
      vehicleId: ''
    }
  });
markers = new this.markerAdv();


setMarkers(id: number) {
    for (let i = 0; i < this.vehicleDetails.length; i++) {

        this.markers = new this.markerAdv(
          [
            this.vehicleDetails[i].position.latitude,
            this.vehicleDetails[i].position.longitude
          ],
          {
            icon: this.myBlueIcon,
            vehicleId: this.vehicleDetails[i].id
          }
        )
          .addTo(this.map)
          .bindPopup(`${this.vehicleDetails[i].name} : ${status}  `)
          .on('mouseover', function(e) {
            this.openPopup();
          })
          .on('mouseout', function(e) {
            this.closePopup();
          })
          .on(
            'click',
            function(event) {
              this.updateInfo(event.target.options.vehicleId);
            },
            this
          );
        
        if (id === this.vehicleDetails[i].id) {
          this.markers.setIcon(this.myBlueSelectedIcon);
        } else {
          this.markers.setIcon(this.myRedIcon);
        }
      }
    }
  }

To prevent overlapping icons and ensure that the correct icon is displayed when selected or cleared, what approach could I take?

Answer №1

After leaving my insight: if you add markers to a leaflet map, they will simply be added and not automatically removed.

If you wish to remove them, manual intervention is required.

To achieve this, keep track of your markers and delete them as needed.

The most efficient method (especially with identifiable markers) is to utilize a Map:

markers: Map<number, Leaflet.Marker> = new Map();

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

What are the best ways to utilize moment and lodash for grouping objects based on fields and counting by dates?

I'm facing a rather complex scenario where I'm looking for a way to manipulate data using lodash and moment. Let's say I have a date range and the following initial data: var startDate = "2018-02-21" var endDate = "2018-02-23" var data = [ ...

How can I transfer a MongoDB collection to an EJS file in the form of a sorted list?

I have successfully displayed the collection as a json object in its own route, but now I want to show the collection in a list under my index.ejs file (I'm still new to ejs and MongoDB). Below is the code that allows me to view the json object at lo ...

Guide: Implementing Vuex store within a plugin

I recently developed a custom Vue plugin which includes a customized instance method import Echo from 'laravel-echo'; import Vue from 'vue'; import config from '@/config'; const echor = { install(Vue){ Vue.prototy ...

The replaceWith() function in jQuery is able to transform PHP code into an HTML comment

How can I change a div element in a click event handler, while ensuring that PHP code inside the element remains intact and does not get moved into an HTML comment? You can find my code snippet below: $("#replaceCat1").click(function(){ $("div.boxconte ...

Information vanishes on mobile devices

After creating a messaging app using React, TypeScript, and Firebase, everything works smoothly locally on both desktop and mobile. However, once the app is deployed, a problem arises specifically on mobile devices. The message input component ("sendMessa ...

Find all documents in Angular Firestore that are related to a specific document_REFERENCE

Seeking a way to search through all documents in collection a that have a reference to a specific document in collection b. Despite my efforts, I couldn't find a solution here or on Google :/ This is what I tried in my service class: getAsFromB(id ...

Error: Unable to locate 'v8' in NextJS when using Twin Macro

I am encountering the error message Module not found: Can't resolve 'v8' when using a package in Nextjs with TypeScript. If I use a .js file, everything works fine. However, when I switch to a .tsx file, it throws a Module Not found error. ...

What is the best way to retain data when a Vue page is about to close?

As far as my understanding goes, it seems that closing or refreshing a page does not trigger the 'beforedestroy' and 'destroyed' hooks in Vue. In order to work around this issue, one possible solution could be to utilize the following ...

Troubleshooting permission problems with Yarn and node_modules in a Docker environment

I have a Docker container containing a Symfony 6 web application and various other services like php-fpm, node, and python. Additionally, I have separate containers for MySQL and Nginx, all running on Alpine 3.15. My current issue arises when I execute do ...

Can the CSS styles of a webpage be modified post-page load?

Hello there! I've been working on implementing a "dark mode/light mode" feature for my website. My approach involves using two different CSS style sheets and toggling between them using a single button So far, I've experimented with various meth ...

curved edges and accentuate the chosen one

I've been working on an angularJS application that includes a webpage with multiple tabs created using angularJS. Check out this example of the working tabs: http://plnkr.co/edit/jHsdUtw6IttYQ24A7SG1?p=preview My goal is to display all the tabs with ...

Angular animation interpolation: a comprehensive guide

<ng-container *ngFor="let item of mainData | keyvalue"> <span [@animate]="states.{{item.key}}"> ////////////////////////////// </span> </ng-container> An error message pops up indicating "Expected ex ...

NodeJs simple mock: Capturing query string parameters with ease

I'm currently developing a basic mock server using only JavaScript and Yarn. Simply put, I have this functional code snippet: function server() { (...) return { users: generate(userGenerator, 150) } This piece of code successfully generates 15 ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Issues arise when the condition fails to function correctly during the process of form

I am currently working on a question from my elder brother's question paper, but I am struggling to solve it. The task is to create a form with two text fields, a radio button, and a submit button. The text fields should be named "account number" and ...

Error: In Nodejs Promises, you cannot invoke the "then" method on an undefined value

Could you clarify what's incorrect about the following code snippet? var promise = fs.readFile(file); var promise2 = promise.then(function(data){ var base64 = new Buffer(data, 'binary').toString('base64'); res.e ...

Is it possible to replicate a slow image loading experience in React.js?

Referenced the solution below How to simulate slow loading of image Slowing down internet connection with Chrome DevTools works, but the entire site loads slowly. I want to specifically focus on slowing down the image reloading. One of the suggestions w ...

Issue encountered during the execution of npm run build with webpack in React Typescript

I have a project using typescript with React, and I am trying to run npm run build to create a dist folder with the bundle.js file. However, I keep encountering an error despite my attempts to resolve it. The specific error message is: npm run build > ...

Using Javascript to Assign Value to Variables

I have been working on this code snippet: http://jsfiddle.net/9B84H/26/ function autosuggest() { var input = document.getElementById('location'); var options = {types: [],}; var autocomplete = new google.maps.places.Autocomplete(input, o ...

Unable to pass a $scope variable into an Angular filter due to interpolation error

In my Angular application, I have a filter that takes a user ID and converts it into a user image URL. It does this by checking if the ID exists in an array and returning the corresponding image URL from the array passed to the filter. The filter is fu ...