动态添加听众到谷歌地图标记 [英] Dynamically Adding Listeners To Google Maps Markers

查看:141
本文介绍了动态添加听众到谷歌地图标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Javascript httpObject获取代码的页面,并使用它来更新页面上的两个元素 - 一个谷歌地图,一个DIV列出标记指向的内容。

I'm working on a page which fetches code with a Javascript httpObject and uses it to update two elements on the page - a google map, and a DIV that lists the things the marker points to.

这一点工作正常。问题是,当我创建标记时,我通过for循环来完成,并且在每个循环中将侦听器添加到标记中。然后,当我测试页面时,我发现每个标记都会发生同样的情况。

That bit works fine. The problem is that when I create the markers, I do so through a for loop, and I add listeners to the marker in each loop. Then, when I test the page, I find the same thing happens for every marker.

悬停在标记上会改变DIV相应位的边框颜色。相反,每个标记都会更改最后一位的边界。似乎每次添加侦听器时,我都会覆盖之前添加的标记的侦听器。

Hovering over a marker should change the border colour of the corresponding bit of the DIV. Instead, each marker changes the border of the last bit. It seems like each time I add the listeners I overwrite the listeners of the previously added markers too.

我知道这与Google Maps API保留身份有关即使在Javascript中创建新标记时也是如此。我没有得到它如何解决它 - 我试图在循环外创建一个数组,并更改

I get that this is to do with the Google Maps API retaining the identity of a marker even when you create a new one in Javascript. What I don't get it how to get around it - I tried creating an array outside the loop, and changing

var newMarker = new GMarker(newLatLng);

with
newMarker [count] = new GMarker(newLatLng);

with newMarker[count] = new GMarker(newLatLng);

但它仍然无效。

帮助我,StackOverflow。你是我唯一的希望。 :)

Help Me, StackOverflow. You're my only hope. :)

编辑:多一点代码

A little more code

for (count=0;count<=LatArray.length;count++)
{
  thisLat = LatArray[count];
  thisLong = LongArray[count];
  thisHTML = HTMLArray[count];
  newLatLng = new GLatLng(thisLat, thisLong, true);

  if (mapBounds.containsLatLng(newLatLng))
  {
      //alert(count);
      var  dinnerNumber = "dinner_"+count;
      newMarkers[count] = new GMarker(newLatLng); 
      map.addOverlay(newMarkers[count]);
      GEvent.addListener(newMarkers[count],'mouseover',function(){document.getElementById(dinnerNumber).style.borderColor = '#000000';
  });
}// for


推荐答案

- 所有这些监听器共享相同的dinnerNumber变量。试试这个:

Closure issue -- all those listeners share the same dinnerNumber variable. Try this:

GEvent.addListener(newMarkers[count], 'mouseover', (function(dinnerNumber){ return function(){document.getElementById(dinnerNumber).style.borderColor = '#000000';}; })(dinnerNumber));

通过这种方式,每个侦听器都使用自己的dinnerNumber的关闭副本创建。

This way, each listener is created with its own closed copy of dinnerNumber.

这篇关于动态添加听众到谷歌地图标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆