Displaying KML

Overview

This tutorial shows you how to display information of a KML file in a Google map and sidebar. For more information on using KML files in maps, read the guide to KML Layers. Try clicking a marker on the map below to see data in the sidebar.

The section below displays the entire code you need to create the map and sidebar.

var map;
var src = 'https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml';

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-19.257753, 146.823688),
    zoom: 2,
    mapTypeId: 'terrain'
  });

  var kmlLayer = new google.maps.KmlLayer(src, {
    suppressInfoWindows: true,
    preserveViewport: false,
    map: map
  });
  kmlLayer.addListener('click', function(event) {
    var content = event.featureData.infoWindowHtml;
    var testimonial = document.getElementById('capture');
    testimonial.innerHTML = content;
  });
}
<div id="map"></div>
<div id="capture"></div>
html, body {
  height: 370px;
  padding: 0;
  margin: 0;
  }
#map {
 height: 360px;
 width: 300px;
 overflow: hidden;
 float: left;
 border: thin solid #333;
 }
#capture {
 height: 360px;
 width: 480px;
 overflow: hidden;
 float: left;
 background-color: #ECECFB;
 border: thin solid #333;
 border-left: none;
 }
<!-- Replace the value of the key parameter with your own API key. -->
<script async
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Try it yourself

You can experiment with this code in JSFiddle by clicking the <> icon in the top-right corner of the code window.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>KML Click Capture Sample</title>
    <style>
      html, body {
        height: 370px;
        padding: 0;
        margin: 0;
        }
      #map {
       height: 360px;
       width: 300px;
       overflow: hidden;
       float: left;
       border: thin solid #333;
       }
      #capture {
       height: 360px;
       width: 480px;
       overflow: hidden;
       float: left;
       background-color: #ECECFB;
       border: thin solid #333;
       border-left: none;
       }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <div id="capture"></div>
    <script>
      var map;
      var src = 'https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml';

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(-19.257753, 146.823688),
          zoom: 2,
          mapTypeId: 'terrain'
        });

        var kmlLayer = new google.maps.KmlLayer(src, {
          suppressInfoWindows: true,
          preserveViewport: false,
          map: map
        });
        kmlLayer.addListener('click', function(event) {
          var content = event.featureData.infoWindowHtml;
          var testimonial = document.getElementById('capture');
          testimonial.innerHTML = content;
        });
      }
    </script>
    <script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

Getting Started

These are the stages to creating the map and sidebar for this tutorial:

  1. Setting up the KML file
  2. Displaying the KMLlayer
  3. Displaying data in the sidebar

Setting up the KML file for import

Your KML file should conform to the KML standard. For details about this standard, refer the Open Geospatial Consortium website. Google's KML documentation also describes the language, and offers both a reference and conceptual developer documentation.

If you're just learning and don't have a KML file, you can:

  • Use the following KML file for this tutorial:

    https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml
    
  • Find a KML file on the web. You can use Google's filetype search operator.

    Substitute any search term for velodromes, or omit the term altogether to find all KML files.

If you're creating your own file, the code in this example assumes that:

  • You have publicly hosted the file on the internet. This is a requirement for all applications that load KML into a KMLLayer, so that Google's servers can find and retrieve the content to display it on the map.
  • The file is not on a password-protected page.
  • Your features have info window content. You can contain this content in a description element, or include it using an ExtendedData element and entity replacement (read below for more info). Both are accessible as the feature's infoWindowHtml property.

ExtendedData elements

The KML file in this tutorial includes feature information in an ExtendedData element. In order to bring this information into the feature's description, use entity replacement, which is essentially a variable in the BalloonStyle tag.

The table below explains the code for this section.

Code and description
<Style id="west_campus_style">
  <IconStyle>
    <Icon>
      <href>https://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png
      </href>
    </Icon>
  </IconStyle>
  <BalloonStyle>
    <text>$[video]</text>
  </BalloonStyle>
</Style>

The KML file has a single Style element that is applied to all the placemarks.
This Style element assigns a value of #[video] to the BalloonStyle's text element.
The $[x] format tells the KML parser to look for a Data element named video, and to use it as the balloon text.
<Placemark>
    <name>Google West Campus 1</name>
    <styleUrl>#west_campus_style</styleUrl>
    <ExtendedData>
      <Data name="video">
        <value><![CDATA[<iframe width="640" height="360"
          src="https://www.youtube.com/embed/ZE8ODPL2VPI" frameborder="0"
          allowfullscreen></iframe><br><br>]]></value>
      </Data>
    </ExtendedData>
    <Point>
      <coordinates>-122.0914977709329,37.42390182131783,0</coordinates>
    </Point>
</Placemark>

Each Placemark contains an ExtendedData element, which holds the Data element. Notice that each Placemark has a single Data element with a name attribute of video.
The file for this tutorial uses the embedded YouTube video as the value of each Placemark's balloon text.

You can learn more about entity replacement in the Adding Custom Data chapter of the KML documentation.

Displaying the KMLLayer

Initializing the map

This table explains the code for this section.

Code and description
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-19.257753, 146.823688),
    zoom: 2,
    mapTypeId: 'terrain'
  });
}

To display KML on a map, you need to first create the map.
This code creates a new Google Map object, tells it where to center and zoom, and attaches the map to the div.
To learn more about the basics of creating a Google Map, read the Adding a Google Map to your website tutorial.

Creating the KMLLayer

This table explains the code that creates a KMLLayer.

Code and description
var kmlLayer = new google.maps.KmlLayer();

Creates a new KMLLayer object to display your KML.
var src = 'https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml';
var kmlLayer = new google.maps.KmlLayer(src, {
  suppressInfoWindows: true,
  preserveViewport: false,
  map: map
});

The KMLLayer constructor sets the URL of your KML file. It also defines properties for the KMLLayer object that do the following:
  • Tells the layer not to display an info window when clicked.
  • Tells the map to center and zoom to the bounding box of the layer's contents.
  • Sets the map to the Map object created earlier.
The Maps JavaScript API reference guide lists all available options for this layer.
Load your HTML file to display the KML file content as a layer on top of the base map. However, clicking any feature won't result in any action yet.

Displaying data in the sidebar

This section explains the settings that displays info window content in the sidebar when you click a feature on the map. This is done by:

  • Listening for a click event on any of the KMLLayer's features.
  • Grabbing the clicked feature's data.
  • Writing that data to the sidebar.

Adding an event listener

Google Maps provides a function to listen and respond to user events on the map, such as clicks or keyboard keypresses. It adds a listener for such click events.

The table below explains the code for this section.

Code and description
kmlLayer.addListener('click', function(event) {});

The kmlLayer.addListener event listener focuses on the following:
  • The type of event to listen for. In this tutorial, it is the click event.
  • A function to call when the event occurs.
You can learn more about events in the Developer's Guide.

Writing the KML feature data to the sidebar

By this stage of the tutorial, you have captured click events on the layer's features. You can now set the application to write the feature's data and info window content to the sidebar.

The table below explains the code for this section.

Code and description
var content = event.featureData.infoWindowHtml;

Writes the info window content to a variable.
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;

Identifies the div to write to, and replaces the HTML in it with the feature's content.
kmlLayer.addListener('click', function(event) {
  var content = event.featureData.infoWindowHtml;
  var testimonial = document.getElementById('capture');
  testimonial.innerHTML = content;
});

These lines of code become the function within the addListener constructor.

Now each time you click a KML feature on the map, the sidebar updates to display its info window content.

More information

Read more about using KML files.