gpt4 book ai didi

javascript - Google map - 将信息传递给事件监听器

转载 作者:数据小太阳 更新时间:2023-10-29 04:55:45 25 4
gpt4 key购买 nike

我认为这是一个范围问题。由于事件是在我添加了所有监听器之后触发的,因此 num_markers 总是被循环中的下一个循环覆盖。

有什么方法可以将变量传递给事件函数吗?

我尝试过这种方法,但它不适合我。 Google Maps: Event Listener only remembering final value of variable

            var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var info_window = new google.maps.InfoWindow();
var markers = [];
function load_markers() {
var bounds_url = map.getBounds().toUrlValue();
$.ajax({
url:'/retailer-markers?bounds='+bounds_url,
dataType: 'json',
success: function(data) {
for(i = 0; i < data.length; i++) {
var marker_pos = new google.maps.LatLng(data[i]['lat'], data[i]['long']);
//Every time the listener event is called this number is the length of the array
var marker_num = get_markers_count();

markers[marker_num] = new google.maps.Marker({
position: marker_pos,
map: map,
title:data[i]['Title'],
icon: image
});

google.maps.event.addListener(markers[marker_num], 'click', function() {
info_window.setContent('hello');
var pos = markers[marker_num].getPosition();
info_window.setPosition(pos);
info_window.open(map, markers[marker_num]);
});


}
}
});
}

最佳答案

解决方案是使用 this 作为标记的详细信息。可以使用 marker.set('some_var', data);

将任何其他变量设置到标记上
$.ajax({
url:'/retailer-markers?bounds='+bounds_url,
dataType: 'json',
success: function(data) {
for(i = 0; i < data.length; i++) {
var info_window = get_info_window();

var marker_pos = new google.maps.LatLng(data[i]['lat'], data[i]['long']);

marker_num = get_markers_count();

marker = new google.maps.Marker({
position: marker_pos,
map: map,
title:data[i]['Title'],
icon: image
});

markers.push(marker);
marker.set('retailer', data[i]);

google.maps.event.addListener(marker, 'click', function() {
var retailer = this.get('retailer');

info_window.setContent(retailer['name']);
info_window.open(map, this);
});


}
}
});

关于javascript - Google map - 将信息传递给事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3827409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com