1

I'm adding Info Windows to polygons (showing the Zipcode value for each Zipcode boundary polygon on my map). However, the Info Window always displays at the last polygons center point with the last zip codes value. It's like Javascript somehow references either the layer (Polygon), InfoWindow or Zipcode - and thereby overrides the first ones used? I'm not sure if this is a JS issue with object references, that I don't understand - or maybe a problem with the event listeners for the Google Map?

// 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);
    }
}
preyz
  • 3,029
  • 5
  • 29
  • 36
  • Simplest solution, use function closure to associate the polygon with the infowindow contents (a createPolygon function or similar to [this post involving markers](http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – geocodezip Feb 25 '14 at 15:07

1 Answers1

2

Given the comment from geocodezip I modified the way to create the event listener, and now it works:

        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));
preyz
  • 3,029
  • 5
  • 29
  • 36