Google Maps API V3, Listener is behaving strangely

I have created a bunch of markers and infoboxes that I want to link together trough a listener, though the listener seems to fire at start without any click, and if I try to fire the listener with a click on the marker(after closing the box) nothing ever happens.

//Load Markers
function LoadData() {
    //Space Reservation
    var site_arr  = new Array();
    var point_arr = new Array();
    var pasta_arr = new Array();
    //Load All Information
    point_arr = [new google.maps.LatLng(38.629343,-9.191592),
                 new google.maps.LatLng(38.649187,-9.189205)];

    site_arr = ["AAA","BBB"];

    pasta_arr = [1,2];

    //Create Markers and Set InfoBoxes
    for(var i = 0 ; i < site_arr.length ; i++){
        marker_arr[i] = new google.maps.Marker({
               position: point_arr[i]
               ,map: map
               ,title: site_arr[i]
                });

            window_arr[i] = new InfoBox({
             content: site_arr[i]
            });
            google.maps.event.addListener(marker_arr[i], 'click', function(i){
           window_arr[i].open(map,marker_arr[i]);
            }(i));
            }
    return 0;
}

Anyone has any idea of what is going on?

Solved the problem, I'm just posting it because it might be useful for others... Thanks everyone!

//Load Markers function LoadData() { //Space Reservation var site_arr = new Array(); var point_arr = new Array(); var pasta_arr = new Array(); //Load All Information point_arr = [new google.maps.LatLng(38.629343,-9.191592), new google.maps.LatLng(38.649187,-9.189205)];

site_arr = ["AAA",
            "BBB"];

pasta_arr = [1,2];

//Create Markers and Set InfoBoxes
for(i = 0 ; i < site_arr.length ; i++){
    marker_arr[i] = new google.maps.Marker({
        position: point_arr[i]
        ,map: map
        ,title: site_arr[i]
        ,icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
    });

    marker_arr[i]._info = new InfoBox({
         content: pasta_arr[i];
    });
    attachListener(marker_arr[i]);
}
return 0;

}

function attachListener(marker){ google.maps.event.addListener(marker, 'click', function(){ marker._info.open(map,marker); }); return 0; }


You are not adding a function to your listener, but a function value. You display the info windows because you evaluate the listener's function(i) at i during LoadData() . The second problem is that even if you remove the evaluation you will not get the intended index i during the call of the listener. The correct way is something like:

marker_arr[i]._info = window_arr[i];
google.maps.event.addListener(marker_arr[i], 'click', function() {
    var marker = this;
    marker._info.open(map, marker);
});
链接地址: http://www.djcxy.com/p/96192.html

上一篇: MVC5上的Google Map API

下一篇: Google Maps API V3,Listener表现得很奇怪