Multiple “InfoWindow” for array of “markers” on Go

2019-03-06 17:47发布

问题:

Using Google Maps API to add an infoWindow to each marker. Markers come from an array.

Although, infoWindow only shows up for the first marker, not the others. Why? Thanks.

function set_markers(array) {
    var mapOptions = {
        zoom: 13
    }
    for (var i = 0; i < array.length; i++) {
        var single_location = array[i];
        var myLatLng = new google.maps.LatLng(single_location[1], single_location[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: single_location[0]
        });
        var infowindow = new google.maps.InfoWindow({
            content: ""
        });
    }

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent('<h3>'+this.title+'</h3>');
        infowindow.open(map,this);
    });
}

回答1:

var infowindow = new google.maps.InfoWindow();

function set_markers(array) {

    var mapOptions = {
        zoom: 13
    };

    for (var i = 0; i < array.length; i++) {

        var single_location = array[i];
        var myLatLng = new google.maps.LatLng(single_location[1], single_location[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: single_location[0]
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent('<h3>' + this.title + '</h3>');
            infowindow.open(map, this);
        });
    }
}

This is untested since you didn't post a MCVE.