Programming with JViews Maps > Introducing the Main Classes > Readers and Writers > The KML Reader and Writer

There are two ways of reading KML or KMZ files:

This section contains the following topics:

The source code for the Map Builder demonstration, which contains all the code described in this section, can be found at <installdir>/jviews-maps81/samples/mapbuilder/index.html.

The IlvKMLReader Class

This class reads KML features from a specified KML file or catalog. It implements the IlvMapFeatureIterator interface to iterate over the read features.

Using the IlvKMLReader Class to Create Vector Data

To read KML features using the IlvKMLReader object:

  1. Create an IlvKMLReader instance from the path of the KML catalog:
String KMLpath = " C:/maps/KML/places.kmz";
IlvKMLReader reader = new IlvKMLReader(KMLpath);
  1. Create a default renderer:
IlvFeatureRenderer renderer = new IlvDefaultFeatureRenderer();
  1. Iterate over the features, render them with an appropriate IlvFeatureRenderer, and assign them to a manager:
IlvMapFeature feature = reader.getNextFeature();
while(feature != null) {
  // Render map feature into the graphic object.
  IlvGraphic graphic = renderer.makeGraphic(feature,null);
  // Add this object on the first layer of the manager.
  manager.addObject(graphic, 0, false);
  feature = reader.getNextFeature();
}

The IlvKMLDataSource Class

The IlvKMLDataSource class provides a convenient way of creating a set of layers containing KML data in a manager.

Using the IlvKMLDataSource Class to Create Vector Data

To read KML features using the IlvKMLDataSource:

  1. Create an IlvKMLDataSource:
String KMLpath = "C:/maps/KML_0606_ed8/KMLT";
IlvKMLDataSource source = new IlvKMLDataSource(KMLpath); 
  1. Connect this data source to the manager of the view:
source.setManager(getView().getManager());
  1. Start the KML data source:
source.start();

Exporting KML Files

You can export part of a map to a KML (or KMZ) file using the Map Export API (see Map Export API). To do so, set an IlvKMLExporter as the vectorial exporter on the IlvMapExportManager. You can also use the raster exporter, if you want to export an overlaid image.

IlvMapExportManager exportManager = new IlvMapExportManager();
IlvKMLExporter KMLExporter = new IlvKMLExporter();
exportManager.setVectorialExporter(KMLExporter);
exportManager.setRasterExporter(KMLExporter);
 
// Configure KML export (file name).
KMLExporter.setFileName("export.kml");
 
// Set the region of the map to export.
exportManager.setExportRegion(-Math.PI,-Math.PI/2, Math.PI,Math.PI/2);
 
// Export selected map layers of the map.
IlvMapLayer mapLayersToExport[]={/* table of map layers to export*/...};
exportManager.exportMapLayers(mapLayersToExport);