我正在使用Google Javascript Map API来绘制保存在数据库中的所有Resturant 我已经编码了JSON对象并制作了一个标记数组,并在地图上绘制了
var locations = [['You Are Here', position.coords.latitude, position.coords.longitude, 'user.png', 0]];
jsonresturant.forEach(element => {
locations.push([element.site_title, element.site_lat, element.site_long, element.site_logo, element.site_id]);
});
var marker, i;
for (i = 0; i < locations.length; i++) {
var icon = {
url: `<?php echo base_url()?>uploads/logos/${locations[i][3]}`,
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0, 0) // origin
};
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
url: `<?php echo base_url()?>shop/?id=${locations[i][4]}`,
title: locations[i][0],
icon: icon
});
}
现在我要使每个标记都可以点击
google.maps.event.addListener( marker, 'click',
(function(marker, i) {
return function() {
window.location.href = this.url;
};
})(marker, i)
);
答案 0 :(得分:1)
修改代码,以便为每个标记绑定到事件侦听器。这样做时,将标记包装在闭包中非常重要(就像您在第二个代码段中所做的那样),这样才能正确传递标记。
for (i = 0; i < locations.length; i++) {
var icon = {
url: `<?php echo base_url()?>uploads/logos/${locations[i][3]}`,
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0, 0) // origin
};
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
url: `<?php echo base_url()?>shop/?id=${locations[i][4]}`,
title: locations[i][0],
icon: icon
});
// bind to the event for marker
google.maps.event.addListener( marker, 'click',
(function(marker, i) {
return function() {
window.location.href = this.url;
};
})(marker, i)
);
}