【问题标题】:Google maps multiple markers with multiple unique info boxes [duplicate]谷歌用多个独特的信息框映射多个标记[重复]
【发布时间】:2014-03-13 07:07:33
【问题描述】:

我目前正在进行的一个项目需要实现一个带有多个标记和多个信息框的谷歌地图。引用地图 API 这似乎是一个很好的起点:

https://developers.google.com/maps/documentation/javascript/examples/icon-complex

所以我使用此代码作为基础并在此基础上构建。现在我坚持的一点是为每个标记添加一个独特的信息框。这是我的来源

http://jsfiddle.net/jackthedev/asK5v/1/

如您所见,我正在尝试调用数组中选择的对象的第一个元素,该元素非常适用于 lat、long 和 title,而不是 contentstring 变量。

for (var i = 0; i < locations.length; i++) {

    var office = locations[i];
    var myLatLng = new google.maps.LatLng(office[1], office[2]); //works here
    var infowindow = new google.maps.InfoWindow({content: contentString});

    var contentString = 
        '<div id="content">'+
        '<div id="siteNotice">'+
        '</div>'+
        '<h1 id="firstHeading" class="firstHeading">'+ office[0] + '</h1>'+ //doesnt work here
        '<div id="bodyContent">'+ 
        '</div>'+
        '</div>';

    var infowindow = new google.maps.InfoWindow({content: contentString});

    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: globalPin,
        title: office[0], //works here
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,this);
    });
}

要查看我要解释的内容,只需单击上面演示中的每个标记,您就会看到一个标题为“中国”的信息框弹出窗口。出于某种原因,它会为每个标记抓取最后一个对象的第一个元素。

我想要实现的是,如果有意义的话,所有信息框都是唯一的标记?因此,当我点击新加坡的一个标记时,将使用我之前定义的数组对象弹出一个带有新加坡标题的信息框。

谢谢,我希望我已经足够清楚了


【问题讨论】:

    标签: javascript jquery google-maps google-maps-api-3


    【解决方案1】:

    问题是变量infoWindow 在循环的每次迭代中都会被覆盖。通常这不会是一个问题,除了 addListener 内部的部分是一个异步回调,并且在每个被调用时,对 infoWindow 的引用不再正确。

    您可以通过为infoWindow 创建一个闭包来解决此问题,以便每个回调函数都有自己的副本。使用这个:

    google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString));
    

    使用附带的辅助函数:

    function getInfoCallback(map, content) {
        var infowindow = new google.maps.InfoWindow({content: content});
        return function() {
                infowindow.setContent(content); 
                infowindow.open(map, this);
            };
    }
    

    See here for a forked Fiddle.

    【讨论】:

    • 这正是我想要的,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2014-07-18
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多