310 Part IV — Google Earth Hacks
Generating KML from Existing Data.
To demonstrate how easy it is to create a KML document with appropriate information, you
can adapt the data that was generated for the database in Chapter 11 (local Grantham busi-
nesses) and instead generate a KML document.
To generate the information, you follow the same basic method as in Chapter 11 to generate
the XML that was previously parsed by JavaScript. Unlike the Google Maps example, where
the XML was loaded on a business type-by-type basis, you can dump the entire database and
organize the information automatically by type by using the Google Earth folder system. The
Google Earth application can handle the filtering and selection process.
The KML document defines one set of data and therefore has only one folder in it. To further
subdivide information you have to add subfolders. The result is a KML file structure that looks
like this:
Grantham Business Folder
■Banks
■Pharmacies
■Restaurant
■Sports
■Travel
The Perl script for generating the file is as follows:
#!/usr/bin/perl
use DBI;
use strict;
my $dbh = DBI->connect( ‘dbi:mysql:database=mapsbookex;host=db.maps.mcslp.com’,
‘mapsbookex’,
‘examples’,
);
You start with the opening structure. The <open>tag defines that the folder is open and the
contents should be displayed when the file is first opened within Google Earth:
print<<EOF;
<?xml version=”1.0” encoding=”UTF-8”?>
<kml xmlns=”http://earth.google.com/kml/2.0”>
<Folder>
<name>Grantham features</name>
<open>1</open>
EOF
The SQL statement picks all available options but orders the information by type so that the
individual folders can be created: