Angular谷歌地图:在单击新标记时关闭信息窗口

8

我正在使用Angular Google Map:https://angular-maps.com/。 目前默认的功能是打开标记内定义的信息窗口。 当点击新的标记时,旧窗口仍然保持打开状态。我需要在点击另一个标记时关闭信息窗口。 这是HTML代码:

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
          <agm-marker 
              *ngFor="let m of markers; let i = index"
              (markerClick)="clickedMarker(m.label, infoWindow, i)"
              [latitude]="m.lat"
              [longitude]="m.lng"
              [markerDraggable]="m.draggable"                
              [iconUrl]="m.icon">

            <agm-info-window #infoWindow>
              <strong>{{m.name}}</strong><br>
            </agm-info-window>

          </agm-marker>
        </agm-map>

这是当标记被点击时的代码:

clickedMarker(label: string, infoWindow, marker, index: number) {
     if( this.infoWindowOpened ===  infoWindow)
      return;

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

当页面刷新时,它可以正常工作。但是一旦我刷新标记变量,它就会显示这个错误:
ERROR TypeError: Cannot read property 'then' of undefined
at InfoWindowManager.close (info-window-manager.js:48)
at AgmInfoWindow.close (info-window.js:94)
at SearchComponent.clickedMarker (search.component.ts:188)

刷新标记的组件代码:

this.markers.push({
              name: item.Name,  
              lat: parseFloat(item.latitude.toString()),
              lng: parseFloat(item.longitude.toString()),
              draggable: false,      
              icon:'assets/img/marker.png'
            });
4个回答

13

你可以将clickedMarker重写为以下简单代码

previous;
...
clickedMarker(infowindow) {
    if (this.previous) {
      this.previous.close();
    }
    this.previous = infowindow;
  }

在模板中修改您的事件绑定函数

(markerClick)="clickedMarker(infoWindow)"

实时代码在这里


但是当在运行时将新标记推入标记数组时,就会出现错误。以上代码在初始页面加载时运行良好。 - Komal
1
使用答案中的代码,您可以动态添加标记。请参见实时版本 - edkeveked

1
我有同样的问题,infoWindow没有自动关闭。在我的情况下,我有两个按钮在地图上显示收藏和取消收藏图标。我在每次点击“收藏”和“取消收藏”按钮时调用this.infoWindowOpened = nullngOnInint()中,这样每次点击都会将其初始化为null。所以这解决了我的问题。这可能对其他人有帮助。
    ngOnInit() {
      this._mapService.selectedIcon.subscribe((res) => {
        this.infoWindowOpened = null;            
      });
    }
    if (this.infoWindowOpened === infoWindow)
       return;

    if (this.infoWindowOpened !== null && this.infoWindowOpened !== undefined)
        this.infoWindowOpened.close();

    this.infoWindowOpened = infoWindow;

0
我遇到了这个问题,问题在于当您更新数据时,所有信息窗口都会重新呈现。因此,原始信息不再存在,这使得关闭成为不可能。 为了避免这种情况,请使用trackBy函数。

0
你需要在代码中检查未定义的变量:"this.infoWindowOpened !== undefined"。
public clickedMarker(label: string, infoWindow: any, marker: any, index: number) {

    if (this.infoWindowOpened === infoWindow) {
        console.log("window already opened");
        return;
    }

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

1
但是,关闭事件不起作用。我的实际问题是,当我点击另一个标记时,信息窗口应该立即关闭。 - Komal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接