The ArcGIS API for JavaScript version 2.4 introduced support for KML via the KMLLayer class.
To add a KML file(.kml or .kmz) to a map, the KML must be available via a publicly accessible URL. Locally hosted or KML files inside a firewall are not supported. Pass the URL for the KML file to the KMLLayer constructor to create a KLM layer which can then be added to a map:
var kmlUrl = 'http://dl.dropbox.com/u/2654618/kml/Wyoming.kml',
kml = new esri.layers.KMLLayer(kmlUrl);
map.addLayer(kml);
You can access and manipulate a KML layer's features like any other layer. Because of the wide range of feature types that can be stored in a KML file, a KML layer added to a map is internally made up of several layers. An ArcGIS API for JavaScript KML layer can be thought of as more of a group layer rather than a single layer.
Geometries from a KML file are stored as feature layers: one each for points, lines and polygons. Feature layers for a particular geometry type are only created if there are features of that geometry type in the KML file. The getLayers() method returns the layers that make up a KML file. The following code snippet shows how to get a KML layer's layers, checks that a layer has graphics, unions the layer extents and then zooms to the new extent:
var kmlExtent, layers = kml.getLayers();
dojo.forEach(layers, function(lyr) {
if ( lyr.graphics && lyr.graphics.length > 0 ) {
var lyrExtent = esri.geometry.geographicToWebMercator(
esri.graphicsExtent(lyr.graphics)
);
if ( globals.kmlExtent ) {
kmlExtent = kmlExtent.union(lyrExtent);
} else {
kmlExtent = lyrExtent;
}
});
map.setExtent(kmlExtent);
Because KML layers use feature layers, there are extensive options for interaction. Some of the things available are selecting features and setting renderers. For more information, see the Feature Layer documentation.
With the 2.4 release of the ArcGIS API for JavaScript, the following KML features are supported: