0

我通过 for 循环从 xml 向 Google Map 添加了许多标记。当我单击要弹出的信息窗口的标记时,我收到一条错误消息,指出“无法调用未定义的“打开”方法”。我在这里做错了什么?

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

2 回答 2

2

你需要一个闭包:

infobox[i] = google.maps.event.addListener(marker,'click',function() {
    return function (windowToOpen) {
        windowToOpen.open(the_Map,marker);
    }(infoWindow[i]);
});
于 2012-10-18T19:36:14.200 回答
1

在您执行 infoWindow[i].open 时 i 的值等于 marker.length。您应该为每个信息窗口创建一个上下文

修改代码:

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

}
于 2012-10-18T19:45:17.023 回答