我希望当鼠标悬停在标记上时显示infowindow,这是我在coffeescript中的代码:
$(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)
要在上下文中提问,以下是我在erb文件中触发map:ready
事件的方式:
<% content_for :scripts do %>
<script type="text/javascript">
Gmaps.map.callback = function(){
console.log('callback');
$(document).trigger('map:ready');
}
</script>
<% end %>
<%= yield :scripts %>
答案 0 :(得分:2)
我有完全相同的问题:我不知道为什么,但是当你在Gmaps.map.markers上循环并尝试绑定鼠标悬停监听器函数时,它总是会将标记变量评估为循环中的最后一个标记
我的解决方法是:不要在鼠标悬停功能中使用标记变量,使用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