Hat
Hat

Reputation: 1731

infowindow 'cannot call method "open" of undefined'

I'm adding a number of markers to a Google Map from xml through a for loop. When I click the marker for the infowindow to pop up I get an error stating 'cannot call method "open" of undefined'. What am I doing wrong here?

jQuery

var markers = xml.documentElement.getElementsByTagName('marker');
//function to create unique id
var getMarkerUniqueId = function(lat, lng) {
   return lat + '_' + lng;
}
//function to get lat/lng
var getLatLng = function(lat,lng) {
    return new google.maps.LatLng(lat, lng);
}
//cycle through and create map markers for each xml marker
for (var i = 0; i < markers.length; i++) {
    //create vars to hold lat/lng from database
    var lat = parseFloat(markers[i].getAttribute('lat'));
    var lng = parseFloat(markers[i].getAttribute('lng'));
    //create a unique id for the marker
    var markerId = getMarkerUniqueId(lat, lng);
    var name = markers[i].getAttribute('Type');
    var html = '<b>' + name + '</b>';
    //create the marker on the map
    var marker = new google.maps.Marker({
        map: the_Map,
        position: getLatLng(lat, lng),
        id: 'marker_' + markerId
    });
    //put the markerId into the cache
    markers_arr[markerId] = marker;
    infoWindow[i] = new google.maps.InfoWindow({
        content: html,
        position: getLatLng(lat, lng),
    });
    infobox[i] = google.maps.event.addListener(marker,'click',function() {
        infoWindow[i].open(the_Map,marker);
    });
}

Upvotes: 0

Views: 1408

Answers (2)

Anoop
Anoop

Reputation: 23208

At the time you executing infoWindow[i].open value of i is equals markers.length. you should create a context for each infowindow

modifie Code:

function createContext (marker, iw){

    google.maps.event.addListener(marker,'click',function() {
      iw.open(the_Map,marker);
 /  });
}
for (var i = 0; i < markers.length; i++) {
   ....
 infobox[i] = createContext(marker, infoWindow[i]); 

}

Upvotes: 1

jbabey
jbabey

Reputation: 46657

You need a closure:

infobox[i] = google.maps.event.addListener(marker,'click',function() {
    return function (windowToOpen) {
        windowToOpen.open(the_Map,marker);
    }(infoWindow[i]);
});

Upvotes: 2

Related Questions