]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/lines2kml
Modified the default_option_parser function to return a parser using a VerbatimHelpFo...
[dead/census-tools.git] / bin / lines2kml
1 #!/usr/bin/env python
2
3 """
4 Export line (road) geometries from the database to Keyhole Markup
5 Language (KML). The exported roads should have both a human-readable
6 name and a globally-unique identifier (gid).
7 """
8
9 import os
10 import pgdb
11 import site
12 import sys
13
14 # Basically, add '../src' to our path.
15 # Needed for the imports that follow.
16 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
17
18 import CLI
19 import Configuration.Defaults
20 import ExitCodes
21 import KML
22
23
24 """
25 Parse the command line options. All of these are optional; defaults
26 are provided for the database information and the output is written
27 to stdout.
28 """
29
30 parser = CLI.default_option_parser()
31
32 # Use this module's docstring as the description.
33 parser.description = __doc__
34
35 parser.add_option('-s',
36 '--state',
37 help='The FIPS id of the State whose roads you would like.')
38
39 (options, args) = parser.parse_args()
40
41
42 conn = pgdb.connect(host=options.host,
43 database=options.database,
44 user=options.username)
45
46
47 # We'll use this cursor for all of our queries.
48 cursor = conn.cursor()
49
50 # If no state is passed on the command line, we want to select the
51 # roads for all states. "... WHERE statefp=statefp ..." will
52 # accomplish this.
53 statefp = 'statefp'
54 if (options.state != None):
55 # The statefp column is a string, so we need to add single quotes
56 # if we're going to specify it.
57 statefp = "'%s'" % options.state
58
59 lines_query = """
60 SELECT gid, tlid, fullname, ST_AsKml(the_geom)
61 FROM tiger_lines
62 WHERE statefp=%s
63 """ % statefp
64
65 cursor.execute(lines_query)
66 rows = cursor.fetchall()
67 doc = KML.Document()
68
69 for row in rows:
70 placemark = KML.Placemark()
71
72 # Name = "Street name (tlid)"
73 fullname = row[2]
74
75 if (fullname == None):
76 # Some streets don't have a fullname.
77 fullname = 'Unknown'
78
79 name = KML.Name(fullname + ' (' + str(row[1]) + ')')
80
81 placemark.children.append(name)
82 geometry = KML.RawText(row[3])
83 placemark.children.append(geometry)
84 doc.children.append(placemark)
85
86 doc.print_kml()
87
88 conn.close()