开发者

Google Maps API v3 - infoWindows all have same content

I've been having problems with the infoWindows and Google Maps API v3. Initially, I've ran into the problem that everyone else has of closing infoWindows when opening a new one. I thought to have solved the problem by defining "infowindow" beforehand. Now they close when I click on a new marker, but the content is the same. How should I re-structure my code to make sure the content is the right one each time - and only one infoWindow is open at a given time?

Thank you!

Paul

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) { infowi开发者_运维百科ndow.close(map,marker); }
              infowindow.open(map,marker);
            });
        }
    });

    last = start+count;  


UPDATED

You are calling

infowindow.open(map,marker);

inside an jQuery.each iteration, thus, i think it will be calling the last item in the iteration. Modify your code so you get this inside the jQuery.each iteration.

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)
);

When you see "return function()" I'm using a javascript closure. I've just used this closure for other stuff. I've got rid of other previous variations in my previous answer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜