Created
October 6, 2018 05:58
-
-
Save marcus-crane/377dc89e3fb8100c6b0908f2c44d51df to your computer and use it in GitHub Desktop.
A script for converting LINZ's NZ Road Addressing dataset from a CSV into GeoJSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import sys | |
from geojson import LineString, MultiLineString, Feature, GeometryCollection, FeatureCollection, dumps | |
csv.field_size_limit(sys.maxsize) | |
def cleanup_coord_string(shape): | |
if 'MULTILINESTRING' in shape: | |
shape = shape.replace('MULTILINESTRING', '') | |
else: | |
shape = shape.replace('LINESTRING', '') | |
shape = shape.replace('(', '').replace(')', '') | |
return shape.strip() | |
def transform_line_string_pairs(pair_string, TYPE=LineString): | |
line_string = [] | |
pairs = pair_string.split(',') | |
for pair in pairs: | |
subpair = pair.split(' ') | |
pairing = [] | |
for item in subpair: | |
pairing.append(float(item)) | |
line_string.append(tuple(pairing)) | |
return TYPE(line_string) | |
def save_geojson(feature_set): | |
with open('streets.geojson', 'w') as file: | |
mapdata = FeatureCollection(feature_set) | |
file.write(dumps(mapdata, indent=2)) | |
print('Saved streets.json') | |
def build_props(row): | |
return { | |
'full_road_name': row['full_road_name'], | |
'road_name_label': row['road_name_label'], | |
'road_name_body': row['road_name_body'], | |
'road_name_type': row['road_name_type'], | |
'road_name_suffix': row['road_name_suffix'], | |
'full_road_name_ascii': row['full_road_name_ascii'], | |
'road_name_label_ascii': row['road_name_label_ascii'], | |
'road_name_body_ascii': row['road_name_body_ascii'] | |
} | |
with open('nz-addressing.csv') as csvfile: | |
address_reader = csv.DictReader(csvfile) | |
features = [] | |
for row in address_reader: | |
shape = row['\ufeffWKT'] | |
shape = cleanup_coord_string(shape) | |
item = transform_line_string_pairs(shape) | |
feature = Feature(geometry=item, properties=build_props(row)) | |
features.append(feature) | |
save_geojson(features) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment