#!/usr/bin/env python """ Export line (road) geometries from the database to Keyhole Markup Language (KML). The exported roads should have both a human-readable name and a globally-unique identifier (gid). """ import os import pgdb import site import sys # Basically, add '../src' to our path. # Needed for the imports that follow. site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src') import CLI import Configuration.Defaults import ExitCodes import KML """ Parse the command line options. All of these are optional; defaults are provided for the database information and the output is written to stdout. """ parser = CLI.default_option_parser() # Use this module's docstring as the description. parser.description = __doc__.strip() parser.add_option('-s', '--state', help='The FIPS id of the State whose roads you would like.') (options, args) = parser.parse_args() conn = pgdb.connect(host=options.host, database=options.database, user=options.username) # We'll use this cursor for all of our queries. cursor = conn.cursor() # If no state is passed on the command line, we want to select the # roads for all states. "... WHERE statefp=statefp ..." will # accomplish this. statefp = 'statefp' if (options.state != None): # The statefp column is a string, so we need to add single quotes # if we're going to specify it. statefp = "'%s'" % options.state lines_query = """ SELECT gid, tlid, fullname, ST_AsKml(the_geom) FROM tiger_lines WHERE statefp=%s """ % statefp cursor.execute(lines_query) rows = cursor.fetchall() doc = KML.Document() for row in rows: placemark = KML.Placemark() # Name = "Street name (tlid)" fullname = row[2] if (fullname == None): # Some streets don't have a fullname. fullname = 'Unknown' name = KML.Name(fullname + ' (' + str(row[1]) + ')') placemark.children.append(name) geometry = KML.RawText(row[3]) placemark.children.append(geometry) doc.children.append(placemark) doc.print_kml() conn.close()