我正在使用Angular谷歌地图: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'
});
你可以非常简单地重写你的clickedMarker
如下
previous;
...
clickedMarker(infowindow) {
if (this.previous) {
this.previous.close();
}
this.previous = infowindow;
}
在模板中更改事件绑定功能
(markerClick)="clickedMarker(infoWindow)"
实时代码是here
您需要检查代码中的undefined:“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;
}
我有同样的问题infoWindow没有自动关闭。在我的场景中,我有两个按钮在地图上显示最喜欢和不喜欢的图标。我在ngOnInint()中调用this.infoWindowOpened = null对每个喜欢和不喜欢的按钮点击。所以它将每次点击初始化为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;