谷歌地图 - 多个标记 - 1 InfoWindow问题

use*_*365 4 html javascript google-maps google-maps-api-3

我无法让我的标记显示不同的信息.标记始终显示最后一个"contentString"的内容.

我已经阅读了其他几篇文章但其中没有一篇似乎有所帮助.

这是代码:

    function setMarkers(branches, map) {
        var bounds = new google.maps.LatLngBounds();
        var contentString = null;
        var infowindow = null;
        infowindow = new google.maps.InfoWindow();
        for (var i = 0; i < branches.length; i++) {
            var marker = null;
            branch = branches[i];
            var myLatlngMarker = new google.maps.LatLng(branch[0], branch[1]);
            contentString = '<p>' + branch[3] + '</p>';

            var marker = new google.maps.Marker({
                position: myLatlngMarker,
                map: map,
                title: branch[2]
            });

            google.maps.event.addListener(marker, 'click', function () {
                infowindow.setContent(contentString);
                infowindow.open(map, this);
            });

            bounds.extend(myLatlngMarker);
        }

        map.fitBounds(bounds);
    }
Run Code Online (Sandbox Code Playgroud)

任何人都可以看到我做错了什么?

谢谢

use*_*365 13

对,

我找到了解决方案.我在标记"info"中添加了一个额外的属性,然后从"addlistener"事件"infowindow.setContent(this.info)"中引用它.

这是更新的代码:

function setMarkers(branches, map) {
    var marker = null;
    var infowindow = new google.maps.InfoWindow();
    var bounds = new google.maps.LatLngBounds();

    for (var i = 0; i < branches.length; i++) {
        branch = branches[i];

        var myLatlngMarker = new google.maps.LatLng(branch[0], branch[1]);

        var marker = new google.maps.Marker({
            position: myLatlngMarker,
            map: map,
            title: branch[2],
            info: branch[3],
            icon: '<%=Icon%>'
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(this.info);
            infowindow.open(map, this);
        });

        bounds.extend(myLatlngMarker);
    }

    map.fitBounds(bounds);
}
Run Code Online (Sandbox Code Playgroud)


puc*_*ead 12

它始终显示最后一个contentString的原因是因为这是click事件触发时设置的内容.它会在for循环的每次迭代中被覆盖.

您应该使用闭包分配事件处理程序并将contextString作为参数传递给函数,返回真正的处理程序.

google.maps.event.addListener(marker, 'click', function(content) {
    return function(){
        infowindow.setContent(content);//set the content
        infowindow.open(map,this);
    }
}(contentString));
Run Code Online (Sandbox Code Playgroud)