I would suggest adding all the markers to the map at the beginning (but hide them), keeping references to them in an array. Then when the Polygon is clicked, process through the array testing if google.maps.geometry.poly.containsLocation is true:
function kmlShowPlacemark(pm) {
if (geoXmlDoc.placemarks[pm].polygon) {
map.fitBounds(geoXmlDoc.placemarks[pm].polygon.bounds);
for (var i=0;i<gmarkers.length;i++) {
if (google.maps.geometry.poly.containsLocation(gmarkers[i].getPosition(),geoXmlDoc.placemarks[pm].polygon)) {
gmarkers[i].setMap(map);
} else {
gmarkers[i].setMap(null);
}
}
}
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setMap(null);
if (placemark.polyline) placemark.polyline.setMap(map);
} else {
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(null);
}
}
}
(note: the example below doesn't hide the markers to start, because I wanted to know where they are, clicking on a polygon hides all the markers outside the polygon and shows (again) the ones inside it) working example
To hide the markers when the are first added remove the "map" option from the addMarker function:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon
});
// rest of the code stays the same.