Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - Google Maps - Multiple markers - 1 InfoWindow problem

I can't get my markers to display different infowindows. The markers always display the content of the last "contentString".

I've read a few other posts but none of them seem to help.

This is the code:

    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);
    }

Can anyone see what am I doing wrong?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Right,

I found a solution. I added an extra property to the marker called 'info' and then referenced it from the 'addlistener' event 'infowindow.setContent(this.info)'.

Here is the updated code:

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...