2

我的问题是该功能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);
        }
    })
}));
4

1 回答 1

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调用。

于 2013-04-29T16:19:46.500 回答