Google Maps Events addlistener中的访问变量

时间:2015-10-22 13:52:27

标签: javascript google-maps google-maps-api-3

for(var i in coordenadas){
  google.maps.event.addListener(marker[i], 'click', toggleBounce);
}

togglebonce功能:

function toggleBounce() {
      if (this.getAnimation() != null) {
        this.setAnimation(null);
        var i = "I WANT TO ACCESS OF VARIABLE i"
      } 
      else {
        this.setAnimation(google.maps.Animation.BOUNCE);
      }
    }

在函数toggleBounce()中我如何访问变量i?该变量传递给... addListener(marker [i] ...

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是在创建标记时将其添加为标记的属性(只需小心命名它,使其不与google.maps.Marker的现有属性冲突。)

// or here (since you didn't provide your code that creates the markers)
for(var i in coordenadas){
  marker[i]._index = i;
  google.maps.event.addListener(marker[i], 'click', toggleBounce);
}

function toggleBounce() {
  if (this.getAnimation() != null) {
    this.setAnimation(null);
    var i = this._index;
  } 
  else {
    this.setAnimation(google.maps.Animation.BOUNCE);
  }
}

proof of concept fiddle