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?