我的问题是函数google.maps.event.addListener(marker, 'click', (function()
只有点击第一个标记才有效。单击所有其他标记无效。我希望这个功能能够处理所有标记。这有什么问题?
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
MyApp.xxx = this.position;
infowindow.setContent('x' + name[i][3] + '' + name[i][4] + 'x');
infowindow.open(map, marker);
}
})(marker, i));
}
var markerroad;
google.maps.event.addListener(marker, 'click', (function () {
var request = {
origin: MyApp.xxx,
destination: 'Kaunas',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
})
}));
答案 0 :(得分:1)
您没有在循环中包含第二个addListener
。试试这个:
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
MyApp.xxx = this.position;
infowindow.setContent('x' + name[i][3] + '' + name[i][4] + 'x');
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(marker, 'click', function () {
var request = {
origin: MyApp.xxx,
destination: 'Kaunas',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
}
由于两个addListener
调用都针对同一项(marker
),因此您可以将每个函数中的代码组合在一起,以便只有一个addListener
调用。