Google 地图:多个 InfoWindows 始终显示最后一个值
好吧,我意识到我是第 100 个提出此问题的人,但即使经过几天的研究和尝试不同的事情,我还是无法弄清楚。 我有一个可以在谷歌地图上创建标记的功能。我将向该函数传递坐标以及将在应附加到每个标记的 infoWindow 中显示的 HTML。
许多其他人遇到的问题是,即使在我的超级简单示例中,infoWindow 的内容始终是任何 infoWindow 的最后一个内容集,而不是创建特定标记时设置的内容。
我该如何解决这个问题?
这是我的代码:
var somerandomcounter = 0;
function addMarkerNew(){
markers[somerandomcounter] = new GMarker(new GLatLng(52.3666667+somerandomcounter,9.7166667+somerandomcounter),{title: somerandomcounter});
map.addOverlay(markers[somerandomcounter]);
var marker = markers[somerandomcounter];
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<b>"+somerandomcounter+"</b>");
});
somerandomcounter++;
}
Okay, so I realize I'm the 100th person asking a question about this, but even after researching and trying different things for days now, I can't figure it out.
I have a function that will create markers on a google map. I will pass this function the coordinates as well as the HTML that will be displayed in the infoWindow that should be attached to each marker.
The problem that so many other people have is that even in my super simple example the content of the infoWindow is always the last content set for any infoWindow instead of the content set when creating a specific marker.
How can I fix this?
Here's my code:
var somerandomcounter = 0;
function addMarkerNew(){
markers[somerandomcounter] = new GMarker(new GLatLng(52.3666667+somerandomcounter,9.7166667+somerandomcounter),{title: somerandomcounter});
map.addOverlay(markers[somerandomcounter]);
var marker = markers[somerandomcounter];
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<b>"+somerandomcounter+"</b>");
});
somerandomcounter++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是变量范围。让我们分解一下:
解决此问题的最简单方法是将 somerandomcounter 变量作为参数传递给其中一个函数 - 这将使单击处理程序中的引用保持指向本地范围的变量。有两种方法可以实现此目的:
将计数器作为参数传递给
addMarkerNew
:创建一个新函数来附加点击处理程序,并将计数器传递到该函数中:
The issue here is variable scope. Let's break it down:
The easiest way to fix this is to pass the
somerandomcounter
variable to one of the functions as an argument - this will keep the reference in the click handler pointing to the locally scoped variable. Here are two ways to do this:Pass the counter as an argument to
addMarkerNew
:Make a new function to attach the click handler, and pass the counter into that function: