Reputation: 21795
I want infowindow to appear when mouse is over a marker, here is my code in 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()
This code outputs this on load:
(39.7317, -104.92099999999999)
(35.2638, -118.91200000000003)
(36.6624, -121.64499999999998)
But this on mouse over of each marker(coordinates does not change):
(36.6624, -121.64499999999998)
To put question in context, here is how I am triggering map:ready
event in an erb file:
<% content_for :scripts do %>
<script type="text/javascript">
Gmaps.map.callback = function(){
console.log('callback');
$(document).trigger('map:ready');
}
</script>
<% end %>
<%= yield :scripts %>
Upvotes: 1
Views: 1247
Reputation: 1191
I had the exact same problem: I don't know why, but when you loop on Gmaps.map.markers and try to bind a mouseover listener function, it will always evaluate the marker variable as the last marker in the loop.
My workaround is: don't use the marker variable in your mouseover function, use this
instead which is a Gmaps Marker object, loop on Gmaps.map.markers and find the one that matches.
Here is the modification for your code:
$(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()
I know it's a very inefficient way to implement the mouseover function. At least, it works.
hth
Upvotes: 2