Last active
September 19, 2015 02:09
-
-
Save ckhung/e74282a9a7b60215640a to your computer and use it in GitHub Desktop.
find all "coordinates" field in a geojson file, and output x,y coordinates as csv
This file contains 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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# http://newtoypia.blogspot.tw/2015/08/admin-boundary.html | |
# 「臺灣各級行政區域(縣市/鄉鎮/村里)邊界座標檔, 自選解析度、 存成 csv、 畫成 svg 」 | |
import json, argparse, sys, math, warnings | |
def ispoint(coords): | |
return isinstance(coords, list) and isinstance(coords[0], (int, long, float)) and len(coords)==2 | |
def coords2csv(coords): | |
if ispoint(coords[0]): | |
for p in coords: | |
print '{0:f}{1:s}{2:f}'.format(p[0], args.delimiter, p[1]) | |
else: | |
map(coords2csv, coords) | |
def geojson2csv(gjdata): | |
if isinstance(gjdata, dict): | |
if gjdata['type'] == 'FeatureCollection': | |
map(geojson2csv, gjdata['features']) | |
elif gjdata['type'] == 'Feature': | |
if 'geometry' in gjdata and isinstance(gjdata['geometry'],dict) and 'coordinates' in gjdata['geometry'] and isinstance(gjdata['geometry']['coordinates'],list) and len(gjdata['geometry']['coordinates'])>0: | |
coords2csv(gjdata['geometry']['coordinates']) | |
else: | |
warnings.warn('ignoring "' + gjdata['type'] + '"') | |
return gjdata | |
elif isinstance(gjdata, list): | |
return map(geojson2csv, gjdata) | |
parser = argparse.ArgumentParser(description='find all "coordinates" field in a geojson file, and output x,y coordinates as csv',formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
parser.add_argument('-d', '--delimiter', type=str, | |
default=',', help='delimiter character between fields') | |
parser.add_argument('gjf', nargs='*', default='-', help='path to geojson files') | |
args = parser.parse_args() | |
for fn in args.gjf: | |
gjfile = sys.stdin if fn == '-' else open(fn) | |
gjdata = json.load(gjfile) | |
geojson2csv(gjdata) | |
# https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence | |
if gjfile is not sys.stdin: | |
gjfile.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment