preyz
preyz

Reputation: 3159

Google Maps Info Window for Polygon object reference issue

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

Upvotes: 1

Views: 470

Answers (1)

preyz
preyz

Reputation: 3159

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

Upvotes: 2

Related Questions