简体   繁体   中英

Remove google maps markers in Angular

I am using the @angular/google-maps package to display a Google Map with some markers which like this:

map.html

<google-map>
    <map-marker
        *ngFor="let marker of markers"
        [position]="marker.position">
</google-map>

map.ts

@ViewChild(GoogleMap, { static: false }) map!: GoogleMap;
markers = [] as any;

replaceMarker()
{
    this.markers = [];

     this.markers.push({
         position: {
             lat: lat,
             lng: lng,
        },
        options: {
            animation: google.maps.Animation.DROP,
        },
     });
}

This is not the code but identical to the implementation. The problem I am having, is that when I try and remove all markers then add a new one, the old markers never remove from the map, they just stay there and the other markers just pile on top.

My question is: How do I remove all markers before pushing my new ones to my markers array?

I was getting my data from an observable so I just had to move this.markers = [] into the subscribe() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM