var map; var texas = new google.maps.LatLng(36.3,-102); function initialize() { var mapOptions = { zoom: 9, center: texas }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // I declare an array called kmlArray to store a reference to my kml layers var kmlArray=[]; // I declare a function that expects a position, a title and a kml url var addMarker=function(position, title, kml) { // i'll give each marker an index property equal to the elements in kmlArrays var index=kmlArray.length; var marker = new google.maps.Marker({ map: map, position: position, title: title, index:index }); var ctaLayer = new google.maps.KmlLayer({ url: kml, preserveViewport: true, suppressInfoWindows: true }); // I add the kml layer I just created to my kmlArray. kmlArray.push(ctaLayer); // I add the behavior to the click event on the marker I'm adding google.maps.event.addListener(marker,'click',function() { // I retrieve the index property I gave the marker. var clickedindex=marker.get('index'); console.log('clicked marker ',clickedindex); // I loop through all my kml layers turning them off kmlArray.forEach(function(kml) { kml.setMap(null); }); // I turn on the kml element whose index corresponds to the marker I just clicked kmlArray[clickedindex].setMap(map); }); }; addMarker({lat:36.1,lng:-102},'marker1','https://dl.dropboxusercontent.com/u/3133731/kml/polygon1.kml'); addMarker({lat:36.2,lng:-101.5},'marker2','https://dl.dropboxusercontent.com/u/3133731/kml/polygon2.kml'); addMarker({lat:36.3,lng:-102.5},'marker3','https://dl.dropboxusercontent.com/u/3133731/kml/polygon3.kml'); addMarker({lat:36.27,lng:-100.9},'marker4','https://dl.dropboxusercontent.com/u/3133731/kml/polygon4.kml'); } google.maps.event.addDomListener(window, 'load', initialize);