One way to approach this is by converting kml files to GeoJSON format and utilizing the Data Layer feature instead of directly using Google Maps API. You can achieve this by employing the toGeoJSON library provided by Mapbox, which offers additional functionalities.
An important point to note is that toGeoJSON does not support kmz format, hence you would need to extract the file before processing it. In my experience, I had to adjust the kml polygon as toGeoJSON requires closed polygons with the same first and last coordinate for proper functioning.
To further explore the implementation, you can refer to the code available in this Fiddle link.
//initialize infoWindow object
var infWindow = new google.maps.InfoWindow();
function setMapFromKML(kmlString) {
if (kmlString.length == 0) {
return false;
}
if (typeof toGeoJSON == "undefined") {
alert("toGeoJSON.js not included");
return;
}
var domparser = new DOMParser();
var kml = domparser.parseFromString(kmlString, "text/xml");
var geojson = toGeoJSON.kml(kml);
var features = map.data.addGeoJson(geojson);
var bounds = new google.maps.LatLngBounds();
features.forEach(function(feature) {
feature.getGeometry().forEachLatLng(function(latlng) {
bounds.extend(latlng);
});
});
map.fitBounds(bounds);
map.data.addListener('click', function(event) {
var infContent = GetContent(event);
var latlng;
if (typeof event.feature.getGeometry().get !== "undefined") { //for point
latlng = event.feature.getGeometry().get();
} else { //polygon/multi,etc...
var polybounds = new google.maps.LatLngBounds()
event.feature.getGeometry().forEachLatLng(function(featurelatlng) {
polybounds.extend(featurelatlng);
});
latlng = polybounds.getCenter();
}
openInfowindow(latlng, infContent);
});
}
function GetContent(event) {
var content = '<div><h3>' + event.feature.getProperty('name') + '</h3>' + event.feature.getGeometry().
getType() + '<br></div>';
return content;
}
function openInfowindow(latLng, content) {
var div = document.createElement('div');
div.innerHTML = content;
infWindow.setContent(div);
infWindow.setPosition(latLng);
infWindow.open(map);
}