【发布时间】:2016-06-26 16:24:41
【问题描述】:
我是使用 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>
【问题讨论】:
标签: javascript ruby-on-rails google-maps google-maps-api-3