2012-10-18 89 views
0

我正在通過for循環從xml向Google Map添加一些標記。當我點擊infowindow的標記彈出時,出現一個錯誤,指出「無法調用方法」打開「未定義」。我在這裏做錯了什麼?infowindow'不能調用未定義的方法「打開」

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); 
    }); 
} 
+0

@CristianoFontes,是的,它是在js文件的頂部與文件中的所有其他全局變量聲明爲:VAR信息窗口= { }; – Hat

回答

1

那時的你執行信息窗口[I]。開i的值等於markers.length。你應該創建一個上下文信息窗口每

modifie代碼:

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

} 
2

你需要一個封閉:

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

他可以將addListener綁定到'this'上嗎? –

+0

不這麼認爲..'這個'是被點擊的元素。 – jbabey

相關問題