1
我刚开始使用Google Maps API,并且无法为Rails中的每个标记设置单击事件。我遍历team_locations模型来获取纬度和经度数据并设置每个标记。我将事件监听器放置在循环中,因此每个标记都设置了一个监听器,但单击时,地图始终放大并聚焦我team_locations表中的最后一个项目。我认为这是因为我的标记变量不断更新,而列表中的最后一项是它的设置。有没有什么好的解决方法?点击事件始终使用最后一个标记
<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>
谢谢;标记数组做了诡计! – Shwheelz