Currently exploring the Google Maps API for the first time and facing a challenge in Rails when trying to add a click event for each marker. I am looping through the team_locations model to extract latitude and longitude data in order to set up markers. I have placed the event listener inside the loop to associate it with each marker, but whenever I click on any marker, the map always zooms in and centers on the last item listed in my team_locations table. I suspect this issue is arising because my marker variable gets constantly updated, pointing to the last item in the list. Any suggestions for effective workarounds?
<script>
function initialize() {
// Center the map on the US
var center = new google.maps.LatLng(37.09024, -95.712891);
var mapOptions = {
zoom: 4,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
<% @team_locations.size.times do |i| %>
var teamLatLng = new google.maps.LatLng(<%= @team_locations[i].latitude %>, <%= @team_locations[i].longitude %>);
var marker = new google.maps.Marker({
position: teamLatLng,
map: map,
label: "<%= @team_locations[i].team_id %>"
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
<% end %>
}
google.maps.event.addDomListener(window, "load", initialize);
</script>