I am using Angular 2 google map one of our application. We are loading marker every 5 secs using Sockets. The problem is need to remove previous marker when new marker receive from socket. There is no proper documents in Angular map official site. So thought of destroy components from our app components. And we got all the child components find the following code.
import { Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { Socket } from 'ng2-socket-io';
import { Marker } from './google-map';
import { SebmGoogleMapMarker } from 'angular2-google-maps/core';
@Component({
selector: 'app-google-map',
templateUrl: './google-map.component.html',
styleUrls: ['./google-map.component.scss'],
providers: [SebmGoogleMapMarker]
})
export class GoogleMapComponent implements OnInit {
public lat: number = 51.678418;
public lng: number = 7.809007;
public markers: Marker[] = [];
@ViewChildren(SebmGoogleMapMarker) SebmGoogleMapMarkers: QueryList<SebmGoogleMapMarker>;
constructor(private socket: Socket) { }
ngOnInit() {
this.socket.on('markers', this.setMarkers);
}
setMarkers = (data: Marker[]) => {
this.removeMarkers();
for (let marker of data) {
var model = new Marker(marker);
this.markers.push(model);
}
}
removeMarkers() {
if (this.SebmGoogleMapMarkers.length > 0) {
this.SebmGoogleMapMarkers.forEach((ele) => {
ele.ngOnDestroy();
});
}
}
}
<div class="col-lg-12">
<sebm-google-map [latitude]="lat" [longitude]="lng">
<sebm-google-map-marker *ngFor="let marker of markers" [latitude]="marker.latitude" [longitude]="marker.longitude">
</sebm-google-map-marker>
</sebm-google-map>
</div>
We got all child components but still reference are there SebmGoogleMapMarkers query list. Is there anyway to destroy component angular way?
Actually here my concern is this.SebmGoogleMapMarkers.length is increasing every 5 sec. what i am feeling is application performance will be reduce.
Solution: I made silly mistake forgot to make marker array empty before pushing.