Angular – Close the previous infoWindow with Angular Map @agm

angulargoogle maps

I am asking a question that many people ask, but no one gave a clear answer, almost on AGM (Angular 2 package for Google map)

Here is my code, but my first opened marker does not want to close, and the other markers close half the time

clickedMarker(marker: Marker, infoWindow, index: number) {

   if (this.infoWindow && this.infoWindow !== infoWindow) {
      this.infoWindow.close();
    }
    this.infoWindow = infoWindow;
}

Can someone help me to fix this close problem, using the close function or the event emitter https://angular-maps.com/api-docs/agm-core/components/AgmInfoWindow.html#source

Thanks for your time and help 😉

EDIT : FOUND THE ANSWER

I had my <agm-info-window #infoWindow> displaying multiple information using <a *ngIf="myCondition"..>{{address}}</a> but it looks like it was not rendering the popup when the condition was evaluate to true again.

I replaced it by <a [class.hidden]="!myCondition">..</a> and it fixed the multiple display of markers.

Another good practice is to close when there is a click on map, and to close it if opened :

clickedMap($event) {
   if (this.infoWindow) {
      this.infoWindow.close();
   }
}

It might help in the future… who knows ?

Best Answer

After a long research and unclear solutions a finally got a fine solution for clear previous agm-info-window when a new one is opened

This is my component.html:

 <agm-map (mapClick)="close_window($event)" [fullscreenControl]='true' [mapTypeControl]='true' [latitude]="lat" [longitude]="lng" [zoom]="13" [scrollwheel]="false">
     <div *ngFor="let data of zonas">
        <agm-marker (markerClick)=select_marker(infoWindow) [latitude]="data.latitud" [longitude]="data.longitud">
           <agm-info-window #infoWindow >            
           </agm-info-window>
         </agm-marker>
      </div>
  </agm-map>

And this is my component.ts:

constructor(public apiService: ApiService) {}
infoWindowOpened = null
previous_info_window = null
...
close_window(){
if (this.previous_info_window != null ) {
  this.previous_info_window.close()
  }    
}

select_marker(data,infoWindow){
 if (this.previous_info_window == null)
  this.previous_info_window = infoWindow;
 else{
  this.infoWindowOpened = infoWindow
  this.previous_info_window.close()
 }
 this.previous_info_window = infoWindow
}

So every time a new window will be open it detect the event and closes the previous one, also this is working for closing a opened window if the user clicks outside the window in any other part of the map

Related Topic