【问题标题】:Google Maps API v3: animation_changed event firing twice?Google Maps API v3:animation_changed 事件触发两次?
【发布时间】:2013-08-25 18:10:29
【问题描述】:

我正在使用 v3 的 Google Maps JavaScript API 创建地图。我将标记放在地图上,并为每个标记打开 InfoWindows,并将信息面板添加到侧面 div,但我不希望 InfoWindows 或侧面信息面板在放置动画之后打开完成了,所以我做了一个事件监听器。

google.maps.event.addListener(newMarker, 'animation_changed', function() {
    if (this.animation == null) {
        // Open InfoWindow
        // Add side info panel
    }
});

问题在于,当 Marker 完成删除时,此侦听器会触发两次,并且 if 测试两次都评估为 true。这对 InfoWindow 来说不是问题。一旦打开,它就打开了,第二次调用 .open() 不会做任何事情。但是每个事件的信息 div 被添加到侧面板两次,这是一个问题。现在,我创建了一个非常简单的解决方法:

google.maps.event.addListener(newMarker, 'animation_changed', function() {
    if (this.animation == null && this.dropped != true) {
        this.dropped = true;
        // Open InfoWindow
        // Add side info panel
    }
});

这达到了我的预期效果,但感觉很hacky。有没有更好的方法来做到这一点?我是否错误地调用了监听器?

【问题讨论】:

  • 为什么不移除监听器?

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


【解决方案1】:

哈哈,我完全没想到;谢谢,莫勒博士。在第一次触发后停止收听。

var myListener = google.maps.event.addListener(newMarker, 'animation_changed', function() {
    google.maps.event.removeListener(myListener);
        if (this.animation == null) {
        // Open InfoWindow
        // Add side info panel
    }
});

【讨论】:

  • 你最好把removeListener的调用放在if-condition中(否则addListenerOnce就足够了)
猜你喜欢
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
相关资源
最近更新 更多