具体来说,如何在各自的infoWindow中显示与标记相关的信息?
按照repo上的例子 此处,每个标记都会打开同样的信息。使用旧的angular google maps,你可以很容易地在标记里面插入信息窗口,你想要的任何数据。
我看到一些例子,在模板中用{{contentHere }}设置内容,但那只允许使用字符串。我需要像平常一样使用所有的angular模板的东西。
比方说,我们的模板看起来像repo的例子。
<google-map height="400px"
width="750px"
[center]="center"
[zoom]="zoom">
<map-marker #marker
*ngFor="let place of places"
[position]="{ lat: place.latitude, lng: place.longitude }"
[options]="markerOptions"
(mapClick)="openInfoWindow(marker)">
<map-info-window>
<-- this is what i'm concerned with -->
{{ place.description }}
</map-info-window>
</map-marker>
</google-map>
然后我们添加viewchild,就像repo的例子一样,用同样的方式打开它。
@ViewChild(MapInfoWindow, {static: false}) infoWindow: MapInfoWindow;
openInfoWindow(marker: MapMarker) {
this.infoWindow.open(marker);
}
虽然这样做确实能打开正确的标记,而且标记会反映动态信息,但这会在每个信息窗口中显示相同的内容place.description,这并不奇怪,因为使用的是单个ViewChild。我想出了各种令人费解的方法来解决这个问题,并查看了源代码,但似乎没有一个明显的或内置的解决方案来显示窗口中与标记使用的内容相关的内容。这只是一个基本的例子,看起来很奇怪。
你们中的任何一个人如何去做这件事?
使用ViewChildren,在模板中的for循环中使用index,当marker被点击时传入index,在forEach里面使用index循环所有ViewChildren(带有index的for循环因为某些原因无法打开窗口),然后如果循环的index与传入的index匹配,就打开该窗口。似乎有比这更好的方法,但这是我尝试了很多东西后能想到的所有方法。
在组件中:
@ViewChildren(MapInfoWindow) infoWindowsView: QueryList<MapInfoWindow>;
openInfoWindow(marker: MapMarker, windowIndex: number) {
/// stores the current index in forEach
let curIdx = 0;
this.infoWindowsView.forEach((window: MapInfoWindow) => {
if (windowIndex === curIdx) {
window.open(marker);
curIdx++;
} else {
curIdx++;
}
});
}
In template:
<google-map height="400px"
width="750px"
[center]="center"
[zoom]="zoom">
<map-marker #marker
*ngFor="let place of places; let i = index" <-- added index -->
[position]="{ lat: place.latitude, lng: place.longitude }"
[options]="markerOptions"
(mapClick)="openInfoWindow(marker, index)"> <-- pass in index -->
<map-info-window>
{{ place.description }}
</map-info-window>
</map-marker>
</google-map>
这将会打开信息窗口与相应的标记。