开发者

Plot Multiple Markers with Multiple infowindows on google maps

开发者 https://www.devze.com 2023-04-10 03:51 出处:网络
I have a mapArray that is being created dynamically based on the clients facilities in our database. I\'m trying to loop through them and create a click listener to open each one\'s info window respe

I have a mapArray that is being created dynamically based on the clients facilities in our database.

I'm trying to loop through them and create a click listener to open each one's info window respectively.

Here's what I have so far

for (var i in mapArray) {

    var thislatlng = new google.maps.LatLng(mapArray[i][1], mapArray[i][2]),
    contentString = '<b>' + mapArray[i][6] + '</b><br /><br />' + mapArray[i][3] + '<br /><br /><a href="http://maps.google.com/maps?daddr=' + mapArray[i][3].replace("<br />", " ").replace("#", " ") + '" target ="_blank">Get Directions<\/a>',
    marker = new google.maps.Marker({
        map: map,
        position: thislatlng
    }),
    infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    google.maps.event.addListener(marker, 'click', function() {

        infowindow.op开发者_运维问答en(map, this);
    });
}

But the problem I have is that they all share the same contentString. I managed to get over one problem by changing

infowindow.open(map, marker);

to

infowindow.open(map, this);

But that still isn't solving the window problems.

How can I use open each one's respective infoWindow dynamically? They're just taking the value of the last one.


JavaScript does not have block scope. infoWindow is getting pulled up to the top of the function and every marker winds up pointing to the same one, which is the last window instantiated. You can reuse the same InfoWindow, making sure that you don't get more than one open at the same time, and replace the content based on the clicked marker:

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

for (var i in mapArray) {

    var thislatlng = new google.maps.LatLng(mapArray[i][1], mapArray[i][2]),
        contentString = '<b>' + mapArray[i][6] + '</b><br /><br />' + mapArray[i][3] + '<br /><br /><a href="http://maps.google.com/maps?daddr=' + mapArray[i][3].replace("<br />", " ").replace("#", " ") + '" target ="_blank">Get Directions<\/a>',
        marker = new google.maps.Marker({
            map: map,
            position: thislatlng,
            information: contentString //Just store the string in a property
        });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(this.information); //Recall the property when clicked to set the content of the window
        infowindow.open(map, this);
    });
}

JSFiddle: http://jsfiddle.net/YCW5a/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号