Title: GoogleMaps API: kml on top of polygon
Tags: javascript;html;google-maps-api-3
Question: How can I render my polygon behind the kml layer?

I have a kml layer imported into my Google Maps canvas. Also, I have implemented a polygon, which is drawn on the canvas whenever you click Draw.

The issue is that when you click Draw the polygon is drawn on top of the kml markers. Thus, I cannot click any marker and visualize their respective names. In other words, I would like to be able to know which markers are included inside the drawn polygon, and for that I would need to click the marker and see its corresponding name.

I believe the solution lies in using panes. I am aware of panes and the order in which they are arranged, but I don't know how to implement a solution using them.

To follow, I'm including my code almost exactly as I have it, so you can see what I am talking about and test it yourself. The only difference is that I'm not including my key for GoogleMaps, so where you see API_KEY, replace for your own key. Thanks in advance.

jsfiddle

HTML:

```<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js" type="text/javascript"&gt;</script&gt;
<script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?key=API_KEY&amp;libraries=geometry"&gt;</script&gt;
<script src="GoogleMapTEST.js"&gt;</script&gt;

<style&gt;
    html{ 
    height:100%; 
    margin:0; 
    padding:0;
    }
    body{
    height:60%;
    font-family:'Trebuchet MS',  'Arial', 'Helvetica', 'sans-serif';
    font-size:10pt;
    background-color: LightGray;
    line-height:1.6em;
    }
    #map-canvas {
    width:80%;
    height:500px;
    margin-left: auto;  
    margin-right: auto; 
    margin-top: 50px;   
    margin-bottom: 25px;
    }
    .col2{
    border: #bfbfbf 1px solid;
    vertical-align: middle;
    display: inline;
    width: 39%;
    height: 90px;
    margin-left: 4%;
    }
</style&gt;

<div id="map-canvas"&gt;</div&gt;                                                       

<div&gt;
    <form&gt;
        <fieldset class="col2"&gt;
            Search radius (km): <br&gt;<br&gt;
            <input type="text" id="DrawTxt" value="30"&gt;
            <input type="button" id="DrawBtn" value="Draw"&gt;
        </fieldset&gt;
    </form&gt;
</div&gt;
```

Javascript:

```var map;
var overlays_array = [];                                                            

function initialize()                                                               
{
    var MyLatLng = new google.maps.LatLng(51,-114);                         
    var mapOptions = {                                                              
        center: MyLatLng,
        zoom: 10
    };

    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);    

    $("#DrawBtn").click( function(){                                                
        ClearOverlays();                                                            
        var radius = $("#DrawTxt").val();                                           
        var circle = DrawCircle(map.getCenter(), radius);                            
        AddOverlay(circle);                                                         
    });

    var CP_url = 'https://drive.google.com/uc?export=download&amp;id=0B2KR4Lz3foYEd04za21sMXZYaEE'      
    var CP_options = {
        preserveViewport: true,                                                                     
        map: map                                                                                    
    };
    var CP_layer = new google.maps.KmlLayer(CP_url, CP_options);                                    
}

google.maps.event.addDomListener(window, 'load', initialize);        

function DrawCircle(center, radius)
{
    var nodes = 72;

    var latConv = google.maps.geometry.spherical.computeDistanceBetween( center, new google.maps.LatLng(center.lat()+0.1, center.lng()) )/100;
    var lngConv = google.maps.geometry.spherical.computeDistanceBetween( center, new google.maps.LatLng(center.lat(), center.lng()+0.1) )/100;

    var points = [];
    var step = parseInt(360/nodes)||10;

    for(var i=0; i<=360; i+=step)
    {
        var pint = new google.maps.LatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
        points.push(pint);
    }
    points.push(points[0]); 

    var poly = new google.maps.Polygon({
        paths: points,
        strokeColor: "#00A2FF",                               
        strokeOpacity: 0,                                     
        strokeWeight: 0,                                      
        fillColor: "#80D0FF",                                 
        fillOpacity: 0.3                                      
    });

    return poly;                                              
}

function AddOverlay(overlay)                                  
{
    if(overlay)
    {
        overlay.setMap(map);                                  
        overlays_array.push(overlay);                         
    }
}

function ClearOverlays()                                      
{
    while(overlays_array[0])                                  
    {
        overlays_array.pop().setMap(null);                    
    }
}
```



Here is another answer: One option (if your kml is not too complex) would be to render the KML as normal Google Maps Javascript API objects using a third party parser like geoxml3 or geoxml-v3, then you can control their ordering with respect to the circle.

example

```<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"&gt;</script&gt;
<script&gt;
function initialize() {
  var MyLatLng = new google.maps.LatLng(51,-114);                         
  var mapOptions = {                                                              
    center: MyLatLng,
    zoom: 10
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);    
  geoXml = new geoXML3.parser({
              map: map,
              infoWindow: infowindow,
              singleInfoWindow: true,
              markerOptions: {optimized: false}
          });
 geoXml.parse("http://www.geocodezip.com/geoxml3_test/kml/CPs_Calgary.kml");
// ...
```

example with 494 markers

example with 839 markers

Comment for this answer: Last I checked, with v3 900 points will not cause performance issues.  Not sure what your target environment is though.
Comment for this answer: geoxml3 uses the XmlHttpRequest object for access to the KML, so is subject to that object's [same domain security restriction](http://www.xml.com/pub/a/2005/11/09/fixing-ajax-xmlhttprequest-considered-harmful.html).  Did you host the KML on the same server as the web page?
Comment for this answer: Yes, set the following option to the parser: `singleInfoWindow: false`. Then write code to either "click" on each marker after creation or open its infowindow.
Comment for this answer: I have run into that parser, but my original KML is composed of about 900 points or markers. Thank you.
Comment for this answer: Thanks for your time. I have just tried that and it didn't work. Most likely I'm doing something wrong. I added the script that references the source and then added the rest of your code below `map = new google.maps......`. The line where it is parsed, I substituted with my own url: https://drive.google.com/uc?export=download&id=0B2KR4Lz3foYEd04za21sMXZYaEE
Comment for this answer: no, I have the KML in GoogleDrive and for the web page I use Webmatrix.
Comment for this answer: using geoxml3, would there be a way of having the KML always show the info windows of all markers?
Comment for this answer: Interesting, I will be trying to host the page and file on the same server next week probably. Anyway, would you know how to do what I am trying just using panes or something else?

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:03/03/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><html><google-maps-api-3>', 'Title': 'GoogleMaps API: kml on top of polygon', 'ViewCount': 389, 'id': 28837030, 'user_AboutMe': '<p>Thanks for your help to all this awesome community, I do appreciate the time you take in answering.</p>\n', 'user_AccountId': 5625343.0, 'user_DisplayName': 'Oscar Duran', 'user_Reputation': 117.0, 'user_Views': 28.0, 'user_id': 4453950.0}}