Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 987
user441365 Avatar asked Nov 27 '22 18:11

user441365


2 Answers

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);
}
like image 73
user441365 Avatar answered Dec 05 '22 03:12

user441365


The reason it always displays the last contentString is because that is what it is set to when the click event fires. It gets overwritten in each iteration of the for loop.

You should assign the event handler using a closure and pass contextString as an argument to the function, returning the real handler.

google.maps.event.addListener(marker, 'click', function(content) {
    return function(){
        infowindow.setContent(content);//set the content
        infowindow.open(map,this);
    }
}(contentString));
like image 28
puckhead Avatar answered Dec 05 '22 02:12

puckhead