Reputation: 553
I'm new to using the Google Maps API, and I'm having trouble setting a click event for each marker in Rails. I'm iterating through the team_locations model to get latitude and longitude data and set each marker. I put the event listener inside the loop so each marker is setup with a listener, but on click, the map always zooms and centers on the last item in my team_locations table. I assume it's happening because my marker variable is constantly updated, and the last item in the list is what it's set to. Are there any good workarounds for this?
<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>
Upvotes: 1
Views: 1229
Reputation: 766
Although the following example is using only javascript
, hopefully it will help you.
Put each of your marker into an array, then you can add event listeners.
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://maps.googleapis.com/maps/api/js"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var map;
var marker;
var markers = [];
var team_locations = [
{latitude: 37.090200, longitude: -95.712882, team_id: 1},
{latitude: 37.050710, longitude: -95.675891, team_id: 2},
{latitude: 36.437308, longitude: -95.978816, team_id: 3}
];
function initialize() {
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);
for (var i = 0; i < team_locations.length; i++) {
var teamLatLng = new google.maps.LatLng(team_locations[i].latitude, team_locations[i].longitude);
marker = new google.maps.Marker({
position: teamLatLng,
map: map,
label: team_locations[i].team_id.toString()
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
map.setZoom(8);
map.setCenter(markers[i].getPosition());
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</body>
</html>
Upvotes: 1