I am using Gmaps4rails and have successfully got quite a bit working, but I am a bit stumped. Probably due to my novice JS skills. I have been trying to follow examples in various questions but I am not sure where I am going wrong.
When my map loads the Gmaps.map.callback is working fine, Map is loaded, I click on a marker and the listener event fires.
In my view:
<% content_for :scripts do %>
<script type="text/javascript">
Gmaps.map.callback = function(){
for(var i = 0; i < Gmaps.map.markers.length; i++){
marker = Gmaps.map.markers[i];
google.maps.event.addListener(marker.serviceObject, 'click',
(function(marker){
return function(){
alert(marker.id);
}
})(marker)
)
}
}
</script>
<% end %>
This will alert with the marker id from the json created in the controller.
I then have a search function that updates the location of the map and replaces the markers. This is getting called in an ajax call. So in the controllers .js.erb I do this:
Gmaps.map.replaceMarkers(<%= raw @json %>);
Everything seems fine, my map is loaded with the new markers, but the even listener does not work on the markers.
So my question is, how do I get these new markers to have the Listener for the click event. Do I need to reset the callback somehow? I think it has to run before the map gets loaded but in this case I am not reloading the map, just replacing the markers.
Extract your method to reuse it:
And whenever you replace markers: