1

当鼠标悬停在标记上时,我希望出现 infowindow,这是我在咖啡脚本中的代码:

$(document).on 'map:ready', -> addHoverHandlers()

addHoverHandlers = ->
  # m is Gmap4Rails marker, doc in gmaps4rails.base.js.coffee
  for m in Gmaps.map.markers
    # marker is a Google Maps Marker
    # https://developers.google.com/maps/documentation/javascript/reference#Marker
    marker = m.serviceObject

    console.log marker.getPosition().toString()
    # Show the infowindow when user mouses-in
    google.maps.event.addListener marker, "mouseover", ->
      console.log marker.getPosition().toString()
      m.infowindow.open marker.map, marker

    # Hide the infowindow when user mouses-out
    google.maps.event.addListener marker, "mouseout", ->
      m.infowindow.close()

此代码在加载时输出:

(39.7317, -104.92099999999999)
(35.2638, -118.91200000000003)
(36.6624, -121.64499999999998) 

但这在鼠标悬停在每个标记上时(坐标不变):

(36.6624, -121.64499999999998)

为了在上下文中提出问题,这是我map:ready在 erb 文件中触发事件的方式:

<% content_for :scripts do %>
    <script type="text/javascript">
        Gmaps.map.callback = function(){
            console.log('callback');
            $(document).trigger('map:ready');
        }
    </script>
<% end %>
<%= yield :scripts %>
4

1 回答 1

2

我遇到了完全相同的问题:我不知道为什么,但是当您在 Gmaps.map.markers 上循环并尝试绑定 mouseover 侦听器函数时,它将始终将标记变量评估为循环中的最后一个标记。

我的解决方法是:不要在鼠标悬停函数中使用标记变量,this而是使用Gmaps Marker对象,在 Gmaps.map.markers 上循环并找到匹配的变量。

这是您的代码的修改:

$(document).on 'map:ready', -> addHoverHandlers()

addHoverHandlers = ->
  # m is Gmap4Rails marker, doc in gmaps4rails.base.js.coffee
  for m in Gmaps.map.markers
    # marker is a Google Maps Marker
    # https://developers.google.com/maps/documentation/javascript/reference#Marker
    marker = m.serviceObject

    console.log marker.getPosition().toString()
    # Show the infowindow when user mouses-in
    google.maps.event.addListener marker, "mouseover", ->
      console.log marker.getPosition().toString()
      # Loop on Gmaps.map.markers and find the one using this
      for m2 in Gmaps.map.markers
        if m2.serviceObject == this
          m2.infowindow.open m2.serviceObject.map, m2.serviceObject

    # Hide the infowindow when user mouses-out
    google.maps.event.addListener marker, "mouseout", ->
      m.infowindow.close()

我知道这是实现鼠标悬停功能的一种非常低效的方法。至少,它有效。

hth

于 2013-03-12T03:53:54.290 回答