简体   繁体   English

在谷歌地图上绘制具有多个信息窗口的多个标记

[英]Plot Multiple Markers with Multiple infowindows on google maps

I have a mapArray that is being created dynamically based on the clients facilities in our database. 我有一个mapArray ,它是根据我们数据库中的客户端工具动态创建的。

I'm trying to loop through them and create a click listener to open each one's info window respectively. 我正在尝试遍历它们并创建一个click侦听器来分别打开每个人的信息窗口。

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.open(map, this);
    });
}

But the problem I have is that they all share the same contentString . 但我遇到的问题是它们都共享相同的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? 我怎样才能动态地打开每个人的infoWindow They're just taking the value of the last one. 他们只是拿走了最后一个的价值。

JavaScript does not have block scope. JavaScript没有块范围。 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. infoWindow被拉到函数顶部,每个标记都指向同一个标记,这是实例化的最后一个窗口。 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: 您可以重复使用相同的InfoWindow,确保您不会同时打开多个InfoWindow,并根据单击的标记替换内容:

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/ JSFiddle: http//jsfiddle.net/YCW5a/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM