谷歌地图信息窗口多边形对象引用问题



我正在向多边形添加信息窗口(显示地图上每个邮政编码边界多边形的邮政编码值)。但是,"信息窗口"始终显示在具有最后一个邮政编码值的最后一个面中心点处。就像Javascript以某种方式引用图层(多边形),InfoWindow或Zipcode - 从而覆盖第一个使用的图层?我不确定这是否是对象引用的 JS 问题,我不明白 - 或者可能是 Google 地图的事件侦听器的问题?

// inside a class ...
var self = this;
self.map = The google map object
// ...
self.createZipcodePolygons = function(zipcodes) {
    for (index = 0; index < zipcodes.length; index++) {
        var zipcode = zipcodes[index];
      var layer = new google.maps.Polygon({
        paths: self.polygonToGooglePath(zipcode.polygon),
        strokeColor: '#666',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#666',
        fillOpacity: 0.35,
        editable: true
      });
        layer.infowindow = new google.maps.InfoWindow({
            content: zipcode.value.toString()
        });
        google.maps.event.addListener(layer,'mouseover',function(){
            layer.infowindow.setPosition(new google.maps.LatLng(zipcode.center.lat, zipcode.center.lng));
            layer.infowindow.open(self.map);
        });
        google.maps.event.addListener(layer,'mouseout',function(){
            layer.infowindow.close();
        });
      layer.setMap(self.map);
    }
}

鉴于 geocodezip 的评论,我修改了创建事件侦听器的方式,现在它可以工作了:

        google.maps.event.addListener(layer,'mouseover',(function(layer,zipcode){
            return function() {
                console.log('over');
                infowindow.setContent(zipcode.value.toString());
                infowindow.setPosition(new google.maps.LatLng(zipcode.center.lat, zipcode.center.lng));
                infowindow.open(self.map);
            }
        })(layer,zipcode));

最新更新