Texan78 Texan78 - 26 days ago 6
Javascript Question

Uncaught TypeError: Cannot set property 'infoWindow' of undefined

I am trying to merge some code from an old map into a new map and I am getting the error "Uncaught TypeError: Cannot set property 'infoWindow' of undefined" referring to this line

polygon.infoWindow = new google.maps.InfoWindow({content: html});


From this snippet below. I have infoWindow defined at the top of the script but, for brevity didn't include it.

geoXml.parseKmlString("<Placemark><name>"+name+"</name>"+kml+"</Placemark>");
var html = "<strong>" + event + "</strong><br>Issued For: " + area + "<br>Expires: " +dtstring;
var polygon = geoXml.docs[0].gpolygons[0];
polygon.infoWindow = new google.maps.InfoWindow({content: html});

google.maps.event.addListener(polygon, 'mouseover', function(e) {
var latLng = e.latLng;
this.setOptions({fillOpacity:0.80});
polygon.infoWindow.setPosition(latLng);
polygon.infoWindow.open(map);
});

Answer

If you look at my example (looks like where your code came from), you would have seen the same error (I have fixed that example). It happens when the entry in the FusionTable returned by the query doesn't contain a polygon. The entry in my example is:

event:Special Weather Statement, expires:2013-05-02T18:00:00-06:00

You can defensively code to not create the infowindow if there isn't a polygon:

 var polygon = geoXml.docs[0].gpolygons[0];
 if (polygon) {
   polygon.infoWindow = new google.maps.InfoWindow({content: html});
   google.maps.event.addListener(polygon, 'mouseover', function(e) {
     var latLng = e.latLng;
     this.setOptions({fillOpacity:0.80});
     polygon.infoWindow.setPosition(latLng);
     polygon.infoWindow.open(map);
   });
   google.maps.event.addListener(polygon, 'mouseout', function() {
     this.setOptions({fillOpacity:0.35});
     polygon.infoWindow.close();
   });
 } else console.log("event:"+event+", expires:"+expires);