【问题标题】:Trying to bind multiple InfoWindows to multiple Markers on a Google Map and failing尝试将多个 InfoWindows 绑定到 Google 地图上的多个标记并失败
【发布时间】:2011-01-22 08:59:15
【问题描述】:

我的项目使用 JSON 提要来获取指定纬度和经度边界内的地震信息,本质上是制作一个盒子。我获取这些信息并将所有结果转换为谷歌地图上的标记。我需要每个标记还显示一些附加信息,因此我尝试使用内置的 InfoWindow 对象,这样当您单击标记时,您会打开带有与该标记相关联的一些信息的工具提示。但是我发现无论我点击什么标记,相同的信息窗口总是出现在该组的相同标记上方,我相信它总是在我的循环中创建的最后一个信息窗口。这是代码。

$.getJSON(url, function(json) {
                    for(var i = 0; i < json.earthquakes.length; i++)
                    {
                        var pos = new google.maps.LatLng(json.earthquakes[i].lat, json.earthquakes[i].lng);
                        var info = json.earthquakes[i].lat + ", " + json.earthquakes[i].lng;
                        var marker = new google.maps.Marker({
                            map: map, 
                            position: pos,
                            title: json.earthquakes[i].eqid
                        })
                        var tooltip = new google.maps.InfoWindow({
                            content: info
                        })
                        google.maps.event.addListener(marker, 'click', function() {
                            tooltip.open(map, marker);
                        });
                        markers.push(marker);
                        tooltips.push(tooltip);
                    }               
                });

markers 是地图上所有标记对象的数组,tooltips 是另一个用于存储 infowindows 对象的数组。它们是全球性的。

【问题讨论】:

  • 这是由于闭包的工作方式(标记通过对闭包的引用传递,您想要的是副本)。但是当调用监听器时,this 会引用添加监听器的对象(标记),所以你可以使用this 而不是marker

标签: javascript ajax json google-maps


【解决方案1】:

这是google-maps 标签中的一个非常常见的问题,也是一个容易犯的错误:)。

发生的情况是您的点击事件被异步调用,它正在获取 getJSON 回调中标记变量中的当前值(列表中的最后一个)。

您需要将 addListener 调用包装在一个函数中,以便在单击回调中使用的标记变量周围创建一个闭包:

function listenMarker (marker)
{
    // so marker is associated with the closure created for the listenMarker function call
    google.maps.event.addListener(marker, 'click', function() {
                        tooltip.open(map, marker);
                    });
}

然后从您的主 getJSON 回调(您当前正在调用 addListener 的地方)调用 listenMarker。

【讨论】:

  • 感谢您提供这个简单明了的解决方案。使用 infowindow,您只需将更多参数传递给函数即可添加更多内容。
  • -1:虽然这可行,但不是必需的,因为this 将引用添加侦听器的对象。
【解决方案2】:

将 addListener 调用放在自己的函数中也解决了多个信息窗口都显示相同文本的问题。

【讨论】:

    【解决方案3】:

    你也可以这样做:

    // so marker is associated with the closure created for the listenMarker function call
    google.maps.event.addListener(marker, 'click', function() {
                        tooltip.open(map, this);
                    });
    

    在添加侦听器调用中,“marker”被替换为“this”。因此,您可以将 addListerner 代码放在创建标记的同一点,而不必创建新函数。

    http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/

    查看完整的解决方案和演示:D

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 2015-08-16
    • 2012-06-21
    • 1970-01-01
    • 2018-05-26
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多