]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - bin/lines2kml
Added the Delaware lines to the download_data script.
[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 from optparse import OptionParser
10 import os
11 import pgdb
12 import site
13 import sys
14
15 # Basically, add '../src' to our path.
16 # Needed for the imports that follow.
17 site.addsitedir(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../src')
18
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 # -h (help) Conflicts with -h HOSTNAME
30 parser = OptionParser(add_help_option = False)
31
32 # Use this module's docstring as the description.
33 parser.description = __doc__.strip()
34
35 parser.add_option('-h',
36 '--host',
37 help='The hostname/address where the database is located.',
38 default=Configuration.Defaults.DATABASE_HOST)
39
40 parser.add_option('-d',
41 '--database',
42 help='The database in which the population data are stored.',
43 default=Configuration.Defaults.DATABASE_NAME)
44
45 parser.add_option('-U',
46 '--username',
47 help='The username who has access to the database.',
48 default=Configuration.Defaults.DATABASE_USERNAME)
49
50 parser.add_option('-s',
51 '--state',
52 help='The FIPS id of the State whose roads you would like.')
53
54 (options, args) = parser.parse_args()
55
56
57 conn = pgdb.connect(host=options.host,
58 database=options.database,
59 user=options.username)
60
61
62 # We'll use this cursor for all of our queries.
63 cursor = conn.cursor()
64
65 # If no state is passed on the command line, we want to select the
66 # roads for all states. "... WHERE statefp=statefp ..." will
67 # accomplish this.
68 statefp = 'statefp'
69 if (options.state != None):
70 # The statefp column is a string, so we need to add single quotes
71 # if we're going to specify it.
72 statefp = "'%s'" % options.state
73
74 lines_query = """
75 SELECT gid, tlid, fullname, ST_AsKml(the_geom)
76 FROM tiger_lines
77 WHERE statefp=%s
78 """ % statefp
79
80 cursor.execute(lines_query)
81 rows = cursor.fetchall()
82 doc = KML.Document()
83
84 for row in rows:
85 placemark = KML.Placemark()
86
87 # Name = "Street name (tlid)"
88 fullname = row[2]
89
90 if (fullname == None):
91 # Some streets don't have a fullname.
92 fullname = 'Unknown'
93
94 name = KML.Name(fullname + ' (' + str(row[1]) + ')')
95
96 placemark.children.append(name)
97 geometry = KML.RawText(row[3])
98 placemark.children.append(geometry)
99 doc.children.append(placemark)
100
101 doc.print_kml()
102
103 conn.close()