gpt4 book ai didi

javascript - 功能仅适用于 1 个标记

转载 作者:行者123 更新时间:2023-11-30 05:48:33 24 4
gpt4 key购买 nike

我的问题是函数 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);
}
})
}));

最佳答案

您没有在循环中包含第二个 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调用。

关于javascript - 功能仅适用于 1 个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16281116/

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