You're all set!

To start developing, please head over to our developer documentation.

Activate the Google Maps JavaScript API

To get you started we'll guide you through the Google Developers Console to do a few things first:

  1. Create or choose a project
  2. Activate the Google Maps JavaScript API and related services
  3. Create appropriate keys
Continue

Displaying KML files in your Maps application

Overview

This tutorial shows you how to:

  • Make sure your KML file is set up for import.
  • Create a KMLLayer object.
  • Display the layer.
  • Capture and display feature data in a sidebar.

Try clicking a marker on the map below to see data displayed in the sidebar.

Your KML file

Your KML file should conform to the KML standard, detailed at 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 either:

  • Use the file that we're using in this lesson. It's at

    https://developers.google.com/maps/documentation/javascript/tutorials/westcampus.kml
    
  • Find one on the web. Use Google's filetype search operator:

    You can of course substitute velodromes for any search term, or omit the term altogether to find all KML files.

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

  • Your file is hosted publicly on the internet. This is a requirement for all applications loading KML into a KMLLayer. Google's servers need to be able to find and retrieve the content in order to display it on the map - this also means that the file can't be on a password-protected page.

  • Your features have infowindow content. This content can be contained in a description element, or can be included 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 we're using in this lesson includes feature information in an ExtendedData element. In order to bring this information into the feature's description, we've used entity replacement, which is essentially a variable in the BalloonStyle tag.

The KML file has a single Style element that is applied to all of the Placemarks. That Style element assigns a value of #[video] to the BalloonStyle's text element:

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

This format — $[x] — tells the KML parser to look for a Data element named video, and to use it as the balloon text.

This Data element is contained inside the ExtendedData element of each Placemark. You'll notice that each Placemark has a single Data element with a name attribute of video.

<Placemark>
  <name>Google West Campus 1</name>
  <styleUrl>#west_campus_style</styleUrl>
  <ExtendedData>
    <Data name="video">
      <value><![CDATA[<iframe width="640" height="360"
        src="http://www.youtube.com/embed/ZE8ODPL2VPI" frameborder="0"
        allowfullscreen></iframe><br><br>]]></value>
    </Data>
  </ExtendedData>
  <Point>
    <coordinates>-122.0914977709329,37.42390182131783,0</coordinates>
  </Point>
</Placemark>

So, in our file, the embedded YouTube video is used 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.

Creating and displaying the KMLLayer

Initializing the map

To display KML on a map, you need to first create the map. The code below creates a new Google Map object, tells it where to center and zoom, and attaches the map to the map div.

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

If you'd like to learn more about the basics of creating a Google Map, please read Adding a Google Map to your website.

Creating the KMLLayer

To display your KML, you need to create a new KMLLayer object:

var kmlLayer = new google.maps.KmlLayer();

The KMLLayer constructor takes two arguments:

  • The URL of your KML file.
  • Options for the KMLLayer, such as whether the layer is clickable, and the map to which the layer is to be attached. The Google Maps JavaScript API reference lists all available options for this layer.
var kmlUrl = 'https://developers.google.com/maps/documentation/javascript/tutorials/westcampus.kml';
var kmlOptions = {
  suppressInfoWindows: true,
  preserveViewport: false,
  map: map
};
var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);

In this case, we've:

  • Set the map to the Map object created earlier.
  • Told the layer not to display an info window when clicked.
  • Told the map to center and zoom to the bounding box of the layer's contents.

If you load your HTML file now, you'll see the contents of your KML file displayed as a layer on top of the base map. Clicking any feature, however, won't result in any action.

Displaying feature data in a custom div

When we created the KMLLayer in the last section, we turned off the layer's option to display an info window when clicked. This is because we'd like to display the feature info in a sidebar, instead.

To do this, we must:

  • Listen for a click event on any of the KMLLayer's features.
  • Grab the clicked feature's data.
  • Write 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. For this application, we'll add a listener for click events.

The google.maps.event.addListener event listener takes three arguments:

  • The object on which to listen. In our case, this is the kmlLayer object.
  • The type of event to listen for. This is 'click' in our example.
  • A function to call when the event occurs.
google.maps.event.addListener(kmlLayer, 'click', function(event) {});

You can learn more about events in the Events chapter of the Developer's Guide.

Writing the KML feature data to the sidebar

Now that we're capturing click events on the layer's features, we can tell our application what to do with a feature's data. In our case, we'd like to write the feature's info window content to a sidebar. To do so, we'll first write the info window content to a variable:

var content = event.featureData.infoWindowHtml;

We'll then identify the div to write to, and replace the div's inner HTML with the feature's content:

var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;

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

google.maps.event.addListener(kmlLayer, 'click', function(event) {
  var content = event.featureData.infoWindowHtml;
  var testimonial = document.getElementById('capture');
  testimonial.innerHTML = content;
});

Now, each time a KML feature is clicked, the sidebar is updated to show that feature's info window content. Pretty neat!

The entire code

/**
 * @fileoverview Sample showing capturing a KML file click
 *   and displaying the contents in a side panel instead of
 *   an InfoWindow
 */

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

/**
 * Initializes the map and calls the function that creates polylines.
 */
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-19.257753, 146.823688),
    zoom: 2,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });
  loadKmlLayer(src, map);
}

/**
 * Adds a KMLLayer based on the URL passed. Clicking on a marker
 * results in the balloon content being loaded into the right-hand div.
 * @param {string} src A URL for a KML file.
 */
function loadKmlLayer(src, map) {
  var kmlLayer = new google.maps.KmlLayer(src, {
    suppressInfoWindows: true,
    preserveViewport: false,
    map: map
  });
  google.maps.event.addListener(kmlLayer, 'click', function(event) {
    var content = event.featureData.infoWindowHtml;
    var testimonial = document.getElementById('capture');
    testimonial.innerHTML = content;
  });
}


Send feedback about...

Google Maps JavaScript API
Google Maps JavaScript API
Need help? Visit our support page.