Here is a sample google map with three polygons. I am setting the infowindow for each polygon as,
for (var i in coordinates) {
arr = [];
for (var j=0; j < coordinates[i].length; j++) {
arr.push( new google.maps.LatLng(
parseFloat(coordinates[i][j][0]),
parseFloat(coordinates[i][j][1])
));
bounds.extend(arr[arr.length-1])
}
// Construct the polygon.
polygons.push(new google.maps.Polygon({
paths: arr,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
polygons[polygons.length-1].setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"Hello World!"
});
google.maps.event.addListener(polygons[polygons.length-1], 'click', function(event) {
infowindow.open(map);
infoWindow.setPosition(event.latLng);
});
}
But the infowindow is showing at the top left position. How can I set it on the center of clicked polygon?
Two issues:
There is a typo in your click listener code, javascript is case sensitive,
infowindow
andinfoWindow
are different objects, so you are not setting the position of the infowindow correctly.You are currently placing the infowindow at the place that is clicked
infoWindow.setPosition(event.latLng);
.If you want the infowindow in the center of the bounds of the polygon, you need to place it there:
updated fiddle
code snippet:
If you want to place it at the polygons "centroid", you need to compute that and place it there:
jsfiddle