我有一组标记对象markers
。然后我使用for循环向它们添加事件侦听器。但是,我似乎无法弄清楚如何确定点击标记的位置。
以下是我现在的代码:
for(var i = 0; i < this.markers.length; i++) //adds listener to all markers
{
google.maps.event.addListener(this.markers[i], "click", () =>
{
//need to get access to which marker was clicked
});
}
我已尝试将参数传递给箭头函数,但似乎没有任何效果。有任何想法吗?只要函数可以返回正确标记的索引,就不需要箭头函数。
答案 0 :(得分:0)
请阅读文档:https://developers.google.com/maps/documentation/javascript/events#EventClosures
这是一个有效的例子:
function initialize() {
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(1, 1)
};
var locations = [
[new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
[new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
[new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
[new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
[new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
[new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
];
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: locations[i][0],
map: map,
title: locations[i][1]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][2]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
initialize();
#map-canvas {
height: 200px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>