【问题标题】:Google Maps API v3 - infoWindows all have same contentGoogle Maps API v3 - infoWindows 都有相同的内容
【发布时间】:2010-05-22 19:10:24
【问题描述】:

我在使用 infoWindows 和 Google Maps API v3 时遇到了问题。 最初,我遇到了其他人在打开一个新的 infoWindows 时关闭 infoWindows 的问题。 我认为通过事先定义“信息窗口”来解决问题。现在,当我单击新标记时它们会关闭,但内容是相同的。 我应该如何重新构建我的代码以确保内容每次都是正确的 - 并且在给定时间只打开一个 infoWindow?

谢谢!

保罗

var allLatLngs = new Array();
var last = 0;
var infowindow;

function displayResults(start, count){
    if(start === undefined){
        start = last;
    }
    if(count === undefined){
        count = 20;
    }
    jQuery.each(jsresults, function(index, value) {
        if(index >= start && index < start+count){
            var obj = jQuery.parseJSON(value);
        $("#textresults").append(index + ": <strong>" + obj.name + "</strong> " + Math.round(obj.distanz*100)/100 + " km entfernt" + "<br/>");

            var myLatlng = new google.maps.LatLng(obj.geo_lat, obj.geo_lon);
            allLatLngs.push(myLatlng);

        var contentString = '<strong>'+obj.name+'</strong>';

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


            var marker = new google.maps.Marker({
                  position: myLatlng,
                  //title:"Hello World!"
              });
            marker.setMap(map);

            google.maps.event.addListener(marker, 'click', function() {
            if (infowindow) { infowindow.close(map,marker); }
              infowindow.open(map,marker);
            });
        }
    });

    last = start+count;  

【问题讨论】:

    标签: javascript google-maps-api-3


    【解决方案1】:

    更新

    你在打电话

    infowindow.open(map,marker);
    

    在 jQuery.each 迭代中,因此,我认为它将调用迭代中的最后一项。 修改您的代码,以便在 jQuery.each 迭代中得到它。

    var curItem = 1;   
    google.maps.event.addListener(aMarker, "click", function(idx, theContent) {
       return function() {
           alert(idx);  //Should print 1 marker1, 2 for marker 2, to show it's ok.
    
           //Your stuff...
           if (infowindow) { 
              infowindow.close(map,marker); 
           }       
           infowindow.setContent(theContent);  
           infowindow.open(map,marker);
       }
    } (curItem++, contentString)
    );
    

    当你看到“return function()”时,我使用的是javascript closure。我刚刚将这个闭包用于其他东西。我在之前的答案中已经摆脱了其他之前的变化。

    【讨论】:

    • 您好 johncatfish,谢谢您的回答。但是,恐怕我不太了解如何使用它。我已经用您的代码替换了 infowindow.open(map,marker) 但它只会引发错误。你能再解释一下吗?谢谢你,保罗
    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2023-03-30
    • 2016-07-21
    • 2012-03-17
    • 2012-06-21
    • 1970-01-01
    相关资源
    最近更新 更多